Android:RunOnUiThread 与 AsyncTask [英] Android: RunOnUiThread vs AsyncTask
问题描述
我相信 Google 建议开发人员使用 AsyncTask.但是,我想知道它与使用新线程"然后调用RunOnUiThread"在性能和内存效率方面有何不同.
I believe Google suggests developers to use AsyncTask. However, I would like to know how is it different from using 'new Thread' and then calling 'RunOnUiThread' in performance and memory efficiency.
使用 RunOnUithread 的示例:
Example for using RunOnUithread:
// some code #1
Thread t = new Thread("Thread1") {
@Override
public void run() {
// some code #2
runOnUiThread(new Runnable() {
public void run() {
// some code #3 (that needs to be ran in UI thread)
}
});
}
};
t.start();
对比
异步任务:
onPreExecute() {
// some code #1
}
doInBackground() {
// some code #2
}
onPostExecute() {
// some code #3
}
优点/缺点是什么?
我不是在寻找诸如更容易查看代码"、对开发人员很方便"等的答案.我实际上是在寻找幕后的技术差异.
I am not looking for answers like 'easier to see the code', 'convenient for developers' etc. I am actually looking for technical diffrences behind the scene.
例如,下面 Paul Nikonowicz 的回答就是我想看到的答案.(但 AsyncTask 的行为相同)
For example, Paul Nikonowicz's answer below would have been the answer I wanted to see. (But AsyncTask behaves the same)
推荐答案
当您使用 new Thread
时,您实际上是在每次执行时创建一个新线程.AsyncTask
然而,使用最多 128 个线程的静态池,并且只要存在就会重用旧线程.因此,串行运行 AsyncTask 10 次只会创建一个运行该任务 10 次的线程,而不是 10 个线程.
When you use new Thread
you're really creating a new thread every time you execute that. AsyncTask
however, uses a static pool of max 128 threads and will reuse an old thread whenever it exists. So, running AsyncTask 10 times in serial will only create one thread that runs the task 10 times instead of 10 threads.
这是许多人之间的差异之一.
That's one of the differences among many.
这篇关于Android:RunOnUiThread 与 AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!