public abstract class AsyncTask<Params, Progress, Result> {...}
AsyncTask is designed to be a helper class around {@link Thread} and {@link Handler} and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as {@link Executor}, {@link ThreadPoolExecutor} and {@link FutureTask}.
publicfinal AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec, Params... params) { if (mStatus != Status.PENDING) {//保证只能运行一次 switch (mStatus) { case RUNNING: thrownewIllegalStateException("Cannot execute task:" + " the task is already running."); case FINISHED: thrownewIllegalStateException("Cannot execute task:" + " the task has already been executed " + "(a task can be executed only once)"); } }
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() {//insert into the tail public void run() { try { r.run(); } finally { scheduleNext();//取出执行下一任务 } } }); if (mActive == null) { scheduleNext(); } }
//long RUNNER-->FutureTask中field:runner的地址偏移 public void run() { if (state != NEW || !U.compareAndSwapObject(this, RUNNER, null, Thread.currentThread()))//Unsafe--CAS--内存比较 //private volatile Thread runner; //判断runner是否为空若为空则赋值为当前线程并返回true -- runner指向当前线程 return;
//新任务尚未执行,runner为空(赋值成功)---> try { Callable<V> c = callable; if (c != null && state == NEW) { V result; boolean ran; try { result = c.call();//执行Callale#call ran = true; } catch (Throwable ex) { result = null; ran = false; setException(ex); } if (ran) set(result);// } } finally { // runner must be non-null until state is settled to // prevent concurrent calls to run() runner = null; // state must be re-read after nulling runner to prevent // leaked interrupts int s = state; if (s >= INTERRUPTING)//中断,取消 handlePossibleCancellationInterrupt(s); } }
//正常结束任务 protected void set(V v) { if (U.compareAndSwapInt(this, STATE, NEW, COMPLETING)) {//新任务 outcome = v; U.putOrderedInt(this, STATE, NORMAL); // final state --->状态设为NORMAL 正常结束 finishCompletion(); } }
//Removes and signals all waiting threads, invokes done(), and nulls out callable private void finishCompletion() { // assert state > COMPLETING; for (WaitNode q; (q = waiters) != null;) { if (U.compareAndSwapObject(this, WAITERS, q, null)) { for (;;) { Thread t = q.thread; if (t != null) { q.thread = null; LockSupport.unpark(t); } WaitNode next = q.next; if (next == null) break; q.next = null; // unlink to help gc q = next; } break; } }
done();//调用重写方法done
callable = null; // to reduce footprint }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
interface Future:提供cancel(任务取消),
A {@code Future} represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.
The result can only be retrieved using method {@code get} when the computation has completed, blocking if necessary until it is ready.
Cancellation is performed by the {@code cancel} method. Additional methods are provided to determine if the task completed normally or was cancelled.
Once a computation has completed, the computation cannot be cancelled.
If you would like to use a {@code Future} for the sake of cancellability but not provide a usable result, you can declare types of the form {@code Future<?>} and return {@code null} as a result of the underlying task.