Android AsyncTask 线程限制?

我正在开发一个应用程序,我需要更新一些信息每次用户登录到系统,我也使用手机中的数据库。对于所有这些操作(更新、从数据库检索数据等等) ,我使用异步任务。到目前为止,我还不知道为什么我不应该使用它们,但是最近我体验到,如果我做一些操作,我的一些异步任务就会在预执行时停止,而不会跳转到 doInBack。这实在是太奇怪了,所以我开发了另一个简单的应用程序来检查哪里出错了。奇怪的是,当异步任务总数达到5时,我得到了相同的行为,第6个异步任务在预执行时停止。

Android 在 Activity/App 上是否有异步任务的限制?或者只是一些错误,应该报告?有没有人遇到过同样的问题并且找到了解决办法?

密码如下:

只需创建5个这样的线程在后台工作:

private class LongAsync extends AsyncTask<String, Void, String>
{
@Override
protected void onPreExecute()
{
Log.d("TestBug","onPreExecute");
isRunning = true;
}


@Override
protected String doInBackground(String... params)
{
Log.d("TestBug","doInBackground");
while (isRunning)
{


}
return null;
}


@Override
protected void onPostExecute(String result)
{
Log.d("TestBug","onPostExecute");
}
}

然后创建这个线程,它会进入 preExecute 并挂起(它不会进入 doInBack)。

private class TestBug extends AsyncTask<String, Void, String>
{
@Override
protected void onPreExecute()
{
Log.d("TestBug","onPreExecute");


waiting = new ProgressDialog(TestActivity.this);
waiting.setMessage("Loading data");
waiting.setIndeterminate(true);
waiting.setCancelable(true);
waiting.show();
}


@Override
protected String doInBackground(String... params)
{
Log.d("TestBug","doInBackground");
return null;
}


@Override
protected void onPostExecute(String result)
{
waiting.cancel();
Log.d("TestBug","onPostExecute");
}
}
56259 次浏览

All AsyncTasks are controlled internally by a shared (static) ThreadPoolExecutor and a LinkedBlockingQueue. When you call execute on an AsyncTask, the ThreadPoolExecutor will execute it when it is ready some time in the future.

The 'when am I ready?' behavior of a ThreadPoolExecutor is controlled by two parameters, the core pool size and the maximum pool size. If there are less than core pool size threads currently active and a new job comes in, the executor will create a new thread and execute it immediately. If there are at least core pool size threads running, it will try to queue the job and wait until there is an idle thread available (i.e. until another job is completed). If it is not possible to queue the job (the queue can have a max capacity), it will create a new thread (up-to maximum pool size threads) for the jobs to run in. Non-core idle threads can eventually be decommissioned according to a keep-alive timeout parameter.

Before Android 1.6, the core pool size was 1 and the maximum pool size was 10. Since Android 1.6, the core pool size is 5, and the maximum pool size is 128. The size of the queue is 10 in both cases. The keep-alive timeout was 10 seconds before 2.3, and 1 second since then.

With all of this in mind, it now becomes clear why the AsyncTask will only appear to execute 5/6 of your tasks. The 6th task is being queued up until one of the other tasks complete. This is a very good reason why you should not use AsyncTasks for long-running operations - it will prevent other AsyncTasks from ever running.

For completeness, if you repeated your exercise with more than 6 tasks (e.g. 30), you will see that more than 6 will enter doInBackground as the queue will become full and the executor is pushed to create more worker threads. If you kept with the long-running task, you should see that 20/30 become active, with 10 still in the queue.

@antonyt has the right answer but in case you are seeking for a simple solution then you may check out Needle.

With it you can define a custom thread pool size and, unlike AsyncTask, it works on all Android versions the same. With it you can say things like:

Needle.onBackgroundThread().withThreadPoolSize(3).execute(new UiRelatedTask<Integer>() {
@Override
protected Integer doWork() {
int result = 1+2;
return result;
}


@Override
protected void thenDoUiRelatedWork(Integer result) {
mSomeTextView.setText("result: " + result);
}
});

or things like

Needle.onMainThread().execute(new Runnable() {
@Override
public void run() {
// e.g. change one of the views
}
});

It can do even lot more. Check it out on GitHub.

Update: Since API 19 the core thread pool size was changed to reflect the number of CPUs on the device, with a minimum of 2 and maximum of 4 at start, while growing to a max of CPU*2 +1 - Reference

// We want at least 2 threads and at most 4 threads in the core pool,
// preferring to have 1 less than the CPU count to avoid saturating
// the CPU with background work
private static final int CORE_POOL_SIZE = Math.max(2, Math.min(CPU_COUNT - 1, 4));
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;

Also note that while the default executor of AsyncTask is serial (executes one task at a time and in the order in which they arrive), with the method

public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
Params... params)

you can provide an Executor to run your tasks. You may provide the THREAD_POOL_EXECUTOR the under the hood executor but with no serialization of tasks, or you can even create your own Executor and provide it here. However, carefully note the warning in the Javadocs.

Warning: Allowing multiple tasks to run in parallel from a thread pool is generally not what one wants, because the order of their operation is not defined. For example, if these tasks are used to modify any state in common (such as writing a file due to a button click), there are no guarantees on the order of the modifications. Without careful work it is possible in rare cases for the newer version of the data to be over-written by an older one, leading to obscure data loss and stability issues. Such changes are best executed in serial; to guarantee such work is serialized regardless of platform version you can use this function with SERIAL_EXECUTOR.

One more thing to note is that both the framework provided Executors THREAD_POOL_EXECUTOR and its serial version SERIAL_EXECUTOR (which is default for AsyncTask) are static (class level constructs) and hence shared across all instances of AsyncTask(s) across your app process.