安卓:RunOnUiThread VS的AsyncTask [英] Android: RunOnUiThread vs AsyncTask

查看:296
本文介绍了安卓:RunOnUiThread VS的AsyncTask的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信谷歌建议开发者使用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();

VS

AsyncTask的:

AsyncTask:

onPreExecute() {
   // some code #1
}

doInBackground() {
   // some code #2
}

onPostExecute() {
   // some code #3
}

有什么优势/劣势?

What are the advantages / disadvantages?

编辑:

我不是在寻找一张像答案更容易看清code','方便开发等。 我其实寻找的幕后技术diffrences。

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.

例如,下面保罗Nikonowicz的回答将是我想看到的答案。 (但AsyncTask的行为相同)

For example, Paul Nikonowicz's answer below would have been the answer I wanted to see. (But AsyncTask behaves the same)

推荐答案

在使用新帖你真的创建一个新线程每次执行的时间。 的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.

这篇关于安卓:RunOnUiThread VS的AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆