gpt4 book ai didi

android - 如何让两个独立的异步任务分开运行?

转载 作者:太空狗 更新时间:2023-10-29 16:39:30 24 4
gpt4 key购买 nike

在我的应用程序中,我点击了两次按钮,在两次按钮点击中,有两个不同的异步任务正在运行,我的问题是当我点击按钮 1 时,第一个异步任务正在运行意味着当它运行时我点击了第二个按钮和第二个异步任务也开始了,但是在后台,直到第一个异步任务完成,第二个异步任务才开始?

public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
if(position==1)
{

Asynchronoustask1();

}

if(position==2)
{

Asynchronoustask2();
}
}

最佳答案

如果您对 AsyncTask 的实现是正确的,则此行为的可能原因是因为 AsyncTasks 的默认 executor SERIAL_EXECUTOR

并行运行多个 AsyncTask 实例(不是连续的.. 没有一个接一个)。执行它们如下:

if (Build.VERSION.SDK_INT >= 11) {
outstandingTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
outstandingTask.execute();
}

来自documentation :

When first introduced, AsyncTask were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution.

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent. Executor, Object[]) with THREAD_POOL_EXECUTOR.

关于android - 如何让两个独立的异步任务分开运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20368554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com