FutureTask 源碼分析

FutureTask 源碼分析,這個類的原理與我分析android當中的FutureTask類差很少[http://www.cnblogs.com/daxin/p/3802392.html]html

 

public class FutureTask<V> implements RunnableFuture<V> { /** 全部的方法所有委託sync */
    private final Sync sync; public FutureTask(Callable<V> callable) { if (callable == null) throw new NullPointerException(); sync = new Sync(callable); } public FutureTask(Runnable runnable, V result) { sync = new Sync(Executors.callable(runnable, result)); } public boolean isCancelled() { return sync.innerIsCancelled(); } public boolean isDone() { return sync.innerIsDone(); } public boolean cancel(boolean mayInterruptIfRunning) { return sync.innerCancel(mayInterruptIfRunning); } public V get() throws InterruptedException, ExecutionException { return sync.innerGet(); } public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return sync.innerGet(unit.toNanos(timeout)); } protected void done() { } protected void set(V v) { sync.innerSet(v); } protected void setException(Throwable t) { sync.innerSetException(t); } public void run() { sync.innerRun(); } protected boolean runAndReset() { return sync.innerRunAndReset(); } private final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = -7828117401763700385L; /** State value representing that task is ready to run */
        /** 表明起始狀態 */
        private static final int READY     = 0; /** State value representing that task is running */
        /** 表明正在運行中狀態 */
        private static final int RUNNING   = 1; /** State value representing that task ran */
        /** 表明運行完成的狀態 */
        private static final int RAN       = 2; /** State value representing that task was cancelled */
        /** 表明被取消的狀態 */
        private static final int CANCELLED = 4; /** The underlying callable */
        private final Callable<V> callable; /** The result to return from get() */
        private V result; /** The exception to throw from get() */
        private Throwable exception; /** * The thread running task. When nulled after set/cancel, this * indicates that the results are accessible. Must be * volatile, to ensure visibility upon completion. */
        private volatile Thread runner; Sync(Callable<V> callable) { this.callable = callable; } /** * 判斷是否完成或者是否取消 * 傳入0或者1 都返回0 說明任務沒有完成 也沒有取消 */
        private boolean ranOrCancelled(int state) { return (state & (RAN | CANCELLED)) != 0; } /** * AbstractQueuedSynchronizer的模板方法 * 返回1能夠獲取鎖 返回-1說明獲取鎖失敗 * 調用innerIsDone 返回TRUE 說明任務已經執行完畢 * 返回FALSE 說明任務沒有執行完畢 */
        protected int tryAcquireShared(int ignore) { return innerIsDone() ? 1 : -1; } /** * 釋放鎖 將執行當前任務的線程設置爲null */
        protected boolean tryReleaseShared(int ignore) { runner = null; return true; } //判斷任務是否被取消
        boolean innerIsCancelled() { return getState() == CANCELLED; } //判斷任務是否完成(取消也算完成)
        boolean innerIsDone() { return ranOrCancelled(getState()) && runner == null; } //獲取結果
        V innerGet() throws InterruptedException, ExecutionException { //首先調用AbstractQueuedSynchronizer的方法,這個方法會調用子類方法tryAcquireShared 上面有講 //若是當前任務已經完成,那麼當前線程能夠向下運行,不然把當前線程加入隊列阻塞.
            acquireSharedInterruptibly(0); //判斷狀態 若是取消了就拋CancellationException異常.
            if (getState() == CANCELLED) throw new CancellationException(); //若是任務執行過程當中出現異常,這裏包裝一下拋出ExecutionException.
            if (exception != null) throw new ExecutionException(exception); return result; } //獲取結果
        V innerGet(long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException { //調用AbstractQueuedSynchronizer裏的方法 // return tryAcquireShared(arg) >= 0 ||doAcquireSharedNanos(arg, nanosTimeout); // 首先tryAcquireShared調用它獲取鎖,也就是看任務完事沒,若是任務完事了就返回TRUE,那麼執行邏輯同上。 // 若是獲取不到鎖,那麼就阻塞當前線程給定的時間,若是時間到了再次任務還沒完成則拋出異常。
            if (!tryAcquireSharedNanos(0, nanosTimeout)) throw new TimeoutException(); if (getState() == CANCELLED) throw new CancellationException(); if (exception != null) throw new ExecutionException(exception); return result; } void innerSet(V v) { for (;;) { int s = getState(); if (s == RAN) return; if (s == CANCELLED) { // aggressively release to set runner to null, // in case we are racing with a cancel request // that will try to interrupt runner
                    releaseShared(0); return; } //正常完成 設置狀態爲RAN
                if (compareAndSetState(s, RAN)) { result = v; releaseShared(0); done(); //通知子類
                    return; } } } void innerSetException(Throwable t) { for (;;) { int s = getState(); if (s == RAN) return; if (s == CANCELLED) { // aggressively release to set runner to null, // in case we are racing with a cancel request // that will try to interrupt runner
                    releaseShared(0); return; } //設置異常
                if (compareAndSetState(s, RAN)) { exception = t; releaseShared(0); done();//通知子類
                    return; } } } //取消任務
        boolean innerCancel(boolean mayInterruptIfRunning) { for (;;) { int s = getState(); //若是任務已經結束,則返回FALSE
                if (ranOrCancelled(s)) return false; //設置任務的狀態爲CANCELLED
                if (compareAndSetState(s, CANCELLED)) break; } //若是參數mayInterruptIfRunning=TRUE,那麼設置線程的終端狀態
            if (mayInterruptIfRunning) { Thread r = runner; if (r != null) r.interrupt(); } //釋放鎖
            releaseShared(0); //調用子類方法,通知狀態改變
 done(); return true; } void innerRun() { //若是任務不是初始狀態則直接結束
            if (!compareAndSetState(READY, RUNNING)) return; runner = Thread.currentThread(); if (getState() == RUNNING) { // recheck after setting thread
 V result; try { result = callable.call(); } catch (Throwable ex) { //咱們寫的任務方法裏若是出現異常則調用setException
 setException(ex); return; } //設置結果
 set(result); } else { //釋放鎖
                releaseShared(0); // cancel
 } } boolean innerRunAndReset() { if (!compareAndSetState(READY, RUNNING)) return false; try { runner = Thread.currentThread(); if (getState() == RUNNING) callable.call(); // don't set result
                runner = null; return compareAndSetState(RUNNING, READY); } catch (Throwable ex) { setException(ex); return false; } } } }
相關文章
相關標籤/搜索