本文总结自Android实战技巧:深入解析AsyncTask
AsyncTask的两种执行方式
-
execute(Params... params)
Android2.3以前的版本
核心线程数 = 5,同时并发执行5个任务,超过5个则放入缓存队列
Android 3.0以后的版本
核心线程数 = 1,只能一个一个任务进行,超过一个则放入缓存队列
-
executeOnExecutor(Executor exec, Params... params)
Android 3.0以后新增的可自定义线程池的执行方式
executeOnExecutor中Executor 的四种常用参数
-
Executors.newCachedThreadPool()
未设置限制,可并发多个任务的线程池(据说线程上限为128个,未验证)
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... strings) {
return null;
}
}.executeOnExecutor(Executors.newCachedThreadPool(),"");
-
Executors.newFixedThreadPool(n)
设置并发n个任务的线程池
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... strings) {
return null;
}
}.executeOnExecutor(Executors.newFixedThreadPool(7),"");
- AsyncTask.SERIAL_EXECUTOR
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... strings) {
return null;
}
}.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR,"");
效果和直接使用execute一致
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... strings) {
return null;
}
}.execute("");
-
AsyncTask.THREAD_POOL_EXECUTOR
效果和Executors.newCachedThreadPool()一致
new AsyncTask<String, Integer, String>() {
@Override
protected String doInBackground(String... strings) {
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"");