Multithreaded code in AsyncTask doInBackground

时间:2015-08-14 22:45:25

标签: java android multithreading android-asynctask

Can there be a performance benefit to running multithreaded code in the doInBackground() function of the android AsyncTask class? This is a rough sketch of my plan:

private class MyBackgroundTask extends AsyncTask<Integer, Integer, Integer>
{
    protected Integer doInBackground(Integer... vals)
    {
        Thread[] thrds = new Thread[NUM_THREADS];
        //Start all threads
        for(int i = 0; i < thrds.length; ++i)
        {
            thrds[i] = //Initialize threads
            thrds[i].start();
        }
        //Wait for all threads to finish
        for(int i = 0; i < thrds.length; ++i)
            thrds[i].join();
        //Post processing...
        return foo;
    }

    protected void onPostExecute(Integer res)
    {
        //Pass value back to UI class
    }
}

Will this spawn new threads which can be taken advantage of on a multi-core device? For instance, if the threads were each searching a (very-large) array for a maximum value, would there be a performance speed up on a multi-core device? Or will this result in something like "many-to-one" behavior.

One more thing, I want to multi-thread using Threads instead of calling multiple AsyncTasks, because the multi-threading will ultimately be handling domain level processing. I would strongly prefer to decouple the domain level processing from the UI classes so I can reuse the domain level classes with a different UI.

Thanks in advance.

3 个答案:

答案 0 :(得分:1)

您应该使用def locate(filename, s): file= open(filename) line= file.readlines() index = 0; for l in line: print l; index = index + 1 if s in l: return index print locate("/Temp/s.txt","s") ,使用AsyncTask生成自己的主题或使用Thread#start()。你不太可能想要结合这些东西。

默认情况下,

java.util.concurrent.Executor类为您的进程提供一个与UI线程不同的线程。其原因主要是确保任务始终按照启动顺序完成。如果这对您来说不是问题,那么AsyncTask允许您指定要运行的任何其他AsyncTask,并提供一个已调整为具有针对核心数量调整的理想大小池的优秀池在您的目标处理器上。

像这样运行一系列任务:

Executor

对于好奇的Android平台内的代码如下所示:

AsyncTask[] tasks = ...
for (Task task : tasks) {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
}

答案 1 :(得分:0)

  

在Android AsyncTask类的doInBackground()函数中运行多线程代码会有性能优势吗?

不,对我而言,你的想法比普通的AsyncTask引入更多的混乱,看看谷歌所说的&#34; asynctask&#34;是什么问题,例如The Hidden Pitfalls of AsyncTask

答案 2 :(得分:0)

以防万一其他人想知道:

是的,可以提高性能。the image I posted in an above comment可以看出,在ASyncTask上启动新线程会导致多对多行为(假设是多核的)设备)。就我而言,我在问题中发布的解决方案类型对我来说效果很好。正如其他人所指出的那样,ASyncTask确实有一些需要妥善处理的细微之处。但是,在我看来,这通常与多线程编程有关,而不是ASyncTask本身的问题。