1.Android 3.0版本之前的AsyncTask
下面是Android 2.3.7版本的AsyncTask的部分源码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public abstract class AsyncTask<Params, Progress, Result> { private static final String LOG_TAG = "AsyncTask" ; private static final int CORE_POOL_SIZE = 5; private static final int MAXIMUM_POOL_SIZE = 128; private static final int KEEP_ALIVE = 1; private static final BlockingQueue<Runnable> sWorkQueue = new LinkedBlockingQueue<Runnable>(10); private static final ThreadFactory sThreadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AsyncTask #" + mCount.getAndIncrement()); } }; private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory); ... } |
在这里又看到了ThreadPoolExecutor,它的核心线程数是5个,线程池允许创建的最大线程数为128,非核心线程空闲等待新任务的最长时间为10秒。采用的阻塞队列是LinkedBlockingQueue,它的容量为10。3.0版本之前的AsyncTask有一个缺点就是,线程池最大的线程数为128,加上阻塞队列的10个任务,所以AsyncTask最多能同时容纳138个任务,当提交第139任务时就会执行饱和策略,默认抛出RejectedExecutionException异常。
2.Android 7.0版本的AsyncTask
在这里采用Android 7.0版本的AsyncTask作为例子,首先来看AsyncTask的构造函数:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | public AsyncTask() { mWorker = new WorkerRunnable<Params, Result>() { //1 public Result call() throws Exception { mTaskInvoked.set( true ); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); Result result = doInBackground(mParams); Binder.flushPendingCommands(); return postResult(result); } }; mFuture = new FutureTask<Result>(mWorker) { //2 @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch (ExecutionException e) { throw new RuntimeException( "An error occurred while executing doInBackground()" , e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; } |
从注释1处看这个WorkerRunnable实现了Callable
当要执行AsyncTask时,需要调用它的execute方法,代码如下所示。
1 2 3 | public final AsyncTask<Params, Progress, Result> execute(Params... params) { return executeOnExecutor(sDefaultExecutor, params); } |
execute方法又调用了executeOnExecutor方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) { switch (mStatus) { case RUNNING: throw new IllegalStateException( "Cannot execute task:" + " the task is already running." ); case FINISHED: throw new IllegalStateException( "Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)" ); } } mStatus = Status.RUNNING; onPreExecute(); mWorker.mParams = params; //1 exec.execute(mFuture); return this ; } |
这里会首先调用 onPreExecute方法,在注释1处将AsyncTask的参数传给WorkerRunnable,从前面我们知道WorkerRunnable会作为参数传递给了FutureTask,因此,参数被封装到FutureTask中。接下来会调用exec的execute方法,并将mFuture也就是前面讲到的FutureTask传进去。这里exec是传进来的参数sDefaultExecutor,它是一个串行的线程池,它的代码如下所示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | private static class SerialExecutor implements Executor { final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>(); Runnable mActive; public synchronized void execute(final Runnable r) { mTasks.offer( new Runnable() { //1 public void run() { try { r.run(); //2 } finally { scheduleNext(); } } }); if (mActive == null) { scheduleNext(); } } protected synchronized void scheduleNext() { if ((mActive = mTasks.poll()) != null) { THREAD_POOL_EXECUTOR.execute(mActive); } } } |
从注释1处可以看出,当调用SerialExecutor 的execute方法时,会将FutureTask加入到mTasks中。当任务执行完或者当前没有活动的任务时都会执行scheduleNext方法,它会从mTasks取出FutureTask任务并交由THREAD_POOL_EXECUTOR处理。关于THREAD_POOL_EXECUTOR,后面会介绍。从这里看出SerialExecutor是串行执行的。在注释2处可以看到执行了FutureTask的run方法,它最终会调用WorkerRunnable的call方法。
前面我们提到call方法postResult方法将结果投递出去,postResult方法代码如下所示。
1 2 3 4 5 6 7 | private Result postResult(Result result) { @SuppressWarnings( "unchecked" ) Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT, new AsyncTaskResult<Result>( this , result)); message.sendToTarget(); return result; } |
在postResult方法中会创建Message,并将结果赋值给这个Message,通过getHandler方法得到Handler,并通过这个Handler发送消息,getHandler方法如下所示。
1 2 3 4 5 6 7 8 | private static Handler getHandler() { synchronized (AsyncTask. class ) { if (sHandler == null) { sHandler = new InternalHandler(); } return sHandler; } } |
在getHandler方法中创建了InternalHandler,InternalHandler的定义如下所示。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | private static class InternalHandler extends Handler { public InternalHandler() { super(Looper.getMainLooper()); } @SuppressWarnings({ "unchecked" , "RawUseOfParameterizedType" }) @Override public void handleMessage(Message msg) { AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj; switch (msg.what) { case MESSAGE_POST_RESULT: // There is only one result result.mTask.finish(result.mData[0]); break ; case MESSAGE_POST_PROGRESS: result.mTask.onProgressUpdate(result.mData); break ; } } } |
在接收到MESSAGE_POST_RESULT消息后会调用AsyncTask的finish方法:
1 2 3 4 5 6 7 8 | private void finish(Result result) { if (isCancelled()) { onCancelled(result); } else { onPostExecute(result); } mStatus = Status.FINISHED; } |
如果AsyncTask任务被取消了则执行onCancelled方法,否则就调用onPostExecute方法。而正是通过onPostExecute方法我们才能够得到异步任务执行后的结果。
接着回头来看SerialExecutor ,线程池SerialExecutor主要用来处理排队,将任务串行处理。 SerialExecutor中调用scheduleNext方法时,将任务交给THREAD_POOL_EXECUTOR。THREAD_POOL_EXECUTOR同样是一个线程池,用来执行任务。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); 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; private static final int KEEP_ALIVE_SECONDS = 30; private static final BlockingQueue<Runnable> sPoolWorkQueue = new LinkedBlockingQueue<Runnable>(128); public static final Executor THREAD_POOL_EXECUTOR; static { ThreadPoolExecutor threadPoolExecutor = new threadPoolExecutor ( CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS, sPoolWorkQueue, sThreadFactory); threadPoolExecutor.allowCoreThreadTimeOut( true ); THREAD_POOL_EXECUTOR = threadPoolExecutor; } |
THREAD_POOL_EXECUTOR指的就是threadPoolExecutor,他的核心线程和线程池允许创建的最大线程数都是由CPU的核数来计算出来的。它采用的阻塞队列仍旧是LinkedBlockingQueue,容量为128。
到此, Android 7.0版本的AsyncTask的源码就分析完了,在AsyncTask中用到了线程池,线程池中运行线程并且又用到了阻塞队列,因此,本章前面介绍的知识在这一节中做了很好的铺垫。Android 3.0及以上版本用SerialExecutor作为默认的线程,它将任务串行的处理保证一个时间段只有一个任务执行,而3.0之前版本是并行处理的。关于3.0之前版本的缺点在3.0之后版本也不会出现,因为线程是一个接一个执行的,不会出现超过任务数而执行饱和策略。如果想要在3.0及以上版本使用并行的线程处理可以使用如下的代码:
1 | asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "" ); |
其中asyncTask是我们自定义的AsyncTask,当然也可以传入Java提供的线程池,比如传入CachedThreadPool。
1 | asyncTask.executeOnExecutor(Executors.newCachedThreadPool(), "" ); |
也可以传入自定义的线程池:
1 2 3 | Executor exec = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); asyncTask.executeOnExecutor(exec, "" ); |
来自:http://www.jianshu.com/p/ed7d9fb724cf
- 文章2300
- 用户1336
- 访客10858220
挑战点亮生活,征服赋予意义。
语法错误: 意外的令牌“标识符”
全面理解Gradle - 定义Task
Motrix全能下载工具 (支持 BT / 磁力链 / 百度网盘)
谷歌Pixel正在开始起飞?
获取ElementUI Table排序后的数据
Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is
亲测!虚拟机VirtualBox安装MAC OS 10.12图文教程
华为手机app闪退重启界面清空log日志问题
android ndk开发之asm/page.h: not found
手机屏幕碎了怎么备份操作?
免ROOT实现模拟点击任意位置
新手必看修改DSDT教程
thinkpad t470p装黑苹果系统10.13.2