Android基本信息:运行code在UI线程 [英] Android basics: running code in the UI thread
问题描述
在在UI线程运行code的观点考虑,是有任何区别:
MainActivity.this.runOnUiThread(新的Runnable(){
公共无效的run(){
Log.d(UI线程,我的UI线程);
}
});
或
MainActivity.this.myView.post(新的Runnable(){
公共无效的run(){
Log.d(UI线程,我的UI线程);
}
});
和
私有类BackgroundTask扩展的AsyncTask<字符串,太虚,位图> {
保护无效onPostExecute(位图的结果){
Log.d(UI线程,我的UI线程);
}
}
这些都不是precisely相同,但他们都将有相同的净效应。
第一和第二之间的区别是,如果你碰巧的在的执行code,第一个( runOnUiThread(当主应用程序线程)
)将立即执行 Runnable接口。第二个(
后()
)始终放的Runnable
在事件队列的末尾,即使你是已经在主应用程序线程。
第三个,假设你创建并执行 BackgroundTask
的一个实例,会浪费大量的时间抓住一个线程出来的线程池,没有执行默认-op doInBackground()
,才最终做相当于一个后()
。这是至今为止最有效的三个。使用的AsyncTask
如果你确实有工作要做在后台线程,不只是使用 onPostExecute的()
。
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");
}
});
or
MainActivity.this.myView.post(new Runnable() {
public void run() {
Log.d("UI thread", "I am the UI thread");
}
});
and
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.
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.
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基本信息:运行code在UI线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!