问题描述
从UI线程中运行代码的角度来看,有什么区别:
In the viewpoint of running code in the UI thread, is there any difference between:
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
或
MainActivity.this.myView.post(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
和
private class BackgroundTask extends AsyncTask<String, Void, Bitmap> {
protected void onPostExecute(Bitmap result) {
Log.d("UI thread", "I am the UI thread");
}
}
推荐答案
虽然它们都具有相同的最终效果,但它们都不是完全相同的.
None of those are precisely the same, though they will all have the same net effect.
第一个和第二个之间的区别在于,如果您在执行代码时碰巧在主应用程序线程,则第一个(runOnUiThread()
)将立即执行 Runnable
.第二个 (post()
) 总是将 Runnable
放在事件队列的末尾,即使您已经在主应用程序线程上.
The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one (runOnUiThread()
) will execute the Runnable
immediately. The second one (post()
) always puts the Runnable
at the end of the event queue, even if you are already on the main application thread.
第三个,假设你创建并执行了一个BackgroundTask
的实例,会浪费很多时间从线程池中抓取一个线程,去执行一个默认的no-op doInBackground()
,在最终执行相当于 post()
的操作之前.这是迄今为止三者中效率最低的.如果您确实在后台线程中有工作要做,请使用 AsyncTask
,而不仅仅是为了使用 onPostExecute()
.
The third one, assuming you create and execute an instance of BackgroundTask
, will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground()
, before eventually doing what amounts to a post()
. This is by far the least efficient of the three. Use AsyncTask
if you actually have work to do in a background thread, not just for the use of onPostExecute()
.
这篇关于Android 基础:在 UI 线程中运行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!