FutureTask

FutureTask

1 用途

A cancellable asynchronous computation. This class provides a base implementation of Future, with methods to start and cancel a computation, query to see if the computation is complete, and retrieve the result of the computation. The result can only be retrieved when the computation has completed; the get methods will block if the computation has not yet completed. Once the computation has completed, the computation cannot be restarted or cancelled (unless the computation is invoked using runAndReset())

提供可以開始和取消的異步任務、并且執(zhí)行結束后能夠獲取執(zhí)行的結果,一旦執(zhí)行結束后就不能夠重新開始或取消。

2 實現(xiàn)

FutureTask實現(xiàn)了RunnableFuture接口

FutureTask

既然是任務首先看run方法

 public void run() {
        //查看狀態(tài),如果不是new說明已經執(zhí)行,如果是則cas設置worker thread為當前線程  
               //確保任務只被執(zhí)行一次
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            //將構造函數(shù)中構造的callable拿出
            Callable<V> c = callable;
            if (c != null && state == NEW) {    //callable不為空、狀態(tài)為new則執(zhí)行
                V result;
                boolean ran;
                try {
                    result = c.call();  //執(zhí)行call
                    ran = true;
                } catch (Throwable ex) {    //執(zhí)行出錯處理異常
                    result = null;
                    ran = false;
                    setException(ex);
                }
                if (ran)
                    set(result);    //正常執(zhí)行則設置返回返回值
            }
        } 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);
        }
    }

get方法獲取返回值

public V get() throws InterruptedException, ExecutionException {
    int s = state;
    if (s <= COMPLETING)    //如果未完成則進入阻塞隊列
        s = awaitDone(false, 0L);
    return report(s);   //根據(jù)完成情況獲取結果
}

FutureTask根據(jù)任務的狀態(tài)判斷任務執(zhí)行的情況,狀態(tài)以及它們之間的轉換如下

    /**
     * The run state of this task, initially NEW.  The run state
     * transitions to a terminal state only in methods set,
     * setException, and cancel.  During completion, state may take on
     * transient values of COMPLETING (while outcome is being set) or
     * INTERRUPTING (only while interrupting the runner to satisfy a
     * cancel(true)). Transitions from these intermediate to final
     * states use cheaper ordered/lazy writes because values are unique
     * and cannot be further modified.
     *
     * Possible state transitions:
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
     */
    private volatile int state;
    private static final int NEW          = 0;  //新建
    private static final int COMPLETING   = 1;  //執(zhí)行中
    private static final int NORMAL       = 2;  //正常執(zhí)行完
    private static final int EXCEPTIONAL  = 3;  //執(zhí)行異常
    private static final int CANCELLED    = 4;  //取消
    private static final int INTERRUPTING = 5;  //正在等待響應中斷
    private static final int INTERRUPTED  = 6;  //已中斷

3 小結

run方法中將構造 函數(shù)中的callable拿出執(zhí)行,執(zhí)行結果放入實例變量outcome中,get則去取出outcome,根據(jù)state進行通信判斷任務執(zhí)行情況。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容