Runnable,Thread,RunOnUIThread

时间:2015-10-06 08:06:38

标签: android multithreading runnable

今天我通过使用Runnable处理一段代码插入/更新并删除一些数据库内容,成功地加速了我的Android应用程序。但是我也使用了RunOnUiThread()和普通的Thread(),但我不知道这三者之间的差异。我确实知道ASyncTask,但是你如何选择使用什么以及主要区别是什么?

对其他网站的解释/链接非常好。

亲切的问候。

2 个答案:

答案 0 :(得分:1)

When you are modifying some value on UI like (textBox.text) from normal thread it raises an exception. So you have to use RunonUiThread() there to share values with UI and run asynchronously at the same time.

normalThreadMethod(){
textBox.text = "Test";  //Exception   
}

RunOnUIThread(){
textbox.text = "Test"; //no error
}

答案 1 :(得分:1)

Most of the code you write runs on the UI thread, ie main thread, by default. Some operations about Views must be executed on the UI thread. And operations which consume lots of resources should be executed off the UI thread.

You can start a new Thread by calling new Thread(Runnable).start(), then the task will be executed on a non-UI thread. But it's recommended to use a thread pool like ExecutorService to do this, because it reuses the threads.

For an AsyncTask, the code in doInBackground() runs on a non-UI thread from a static thread pool of AsycTask, while onPostExecuted() are executed on the UI thread. So you should do UI operations in onPostExecuted().

When using Handler, where the handleMessage() code runs is based on the Looper you pass to the constructor of Handler. By default, it's Looper.getMainLooper(), so it runs on the UI thread.