在Android 2.3之后,android团队在异步任务方面到底做了什么改变?当我执行以下代码时,我在Android2.3和3.0中都得到了相同的结果。
package com.sample.asynctask;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
public class AsyncTaskTestActivity extends Activity {
private static final String TAG = "AsyncTaskTestActivity";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//ExecutorService executorService = Executors.newFixedThreadPool(1);
for (int i = 1; i <= 20; i++) {
TestTask testTask = new TestTask(i);
testTask.execute();
}
}
private static class TestTask extends AsyncTask<Void, Integer, Void> {
int i;
public TestTask(int i) {
Log.i(TAG, "Constructor for " + i);
this.i = i;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
Log.i(TAG, "onPreExecute for " + i);
}
@Override
protected Void doInBackground(Void... params) {
Log.i(TAG, i + " Thread goes to sleep");
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i(TAG, i + " Thread wakes up");
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Log.i(TAG, "onPostExecute for " + i);
}
}
}我在姜饼中的假设是:5个异步任务一次在一个线程池中执行。我在Honeycomb中的假设是:一个异步任务一次在一个线程池中执行。就像并发执行一样。
但是,姜饼和蜂巢同时执行5个异步任务。
而且,当异步任务的数量增加到140时,我得不到java.util.concurrent.RejectedExecutionException。
我的假设是否正确?里面到底发生了什么?
发布于 2012-06-12 20:24:32
我的假设是否正确?
你的假设是正确的,嗯,某种程度上。
里面到底发生了什么?
android.os.AsyncTask中的默认执行器
... ...
private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
... ...已在android.app.ActivityThread中重置
... ...
// If the app is Honeycomb MR1 or earlier, switch its AsyncTask
// implementation to use the pool executor. Normally, we use the
// serialized executor as the default. This has to happen in the
// main thread so the main looper is set right.
if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
... ...在Android姜饼之后,异步任务到底发生了什么变化?
查看AsyncTask change history,更具体地说,这篇文章:
Mar 17, 2011 - AsyncTask now uses the poll executor for apps up through HC MR1 and t…
当异步任务的数量增加到140时,我得不到java.util.concurrent.RejectedExecutionException.
这是一个任务总数和每个任务的执行时间的因素,在另一个世界中,总任务数是140 (大于128),然而,在任何给定的时间,线程池分配的线程总数都小于128,换句话说,在你的情况下,总是有一些空闲的线程(由于最后一个任务完成和释放资源)。你可以尝试增加每个任务的执行时间,例如Thread.sleep(10000),这可能会给你带来RejectedExecutionException。
发布于 2012-06-12 19:09:28
此线程概述了ICS中对AsyncTask的更改。这些信息是由谷歌员工提供的,因此是值得信赖的。
https://groups.google.com/forum/?fromgroups#!topic/android-developers/8M0RTFfO7-M
发布于 2012-06-12 19:07:42
AsyncTask行为的改变还要求您在in或更高级别的硬件上运行。
请参阅:http://commonsware.com/blog/2012/04/20/asynctask-threading-regression-confirmed.html
https://stackoverflow.com/questions/10995281
复制相似问题