FutureTask原理

前言

FutureTask可以獲取異步執(zhí)行結(jié)果和取消異步操作。我們想看看它的類圖關(guān)系。




從上面的類圖關(guān)系來看,最終線程還是執(zhí)行的Runnable的run方法,只是FutureTask做了一系列的包裝。

FutureTask源碼

首先我們先來看看如何使用FutureTask。

  public static void futureTaskDemo() throws ExecutionException, InterruptedException {
        FutureTask<String> futureTask = new FutureTask<>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                System.out.println("線程"+Thread.currentThread().getName()+",開始睡眠");
                //休眠2秒鐘
                Thread.sleep(2000);
                return "我睡醒了";
            }
        });
        System.out.println("線程"+Thread.currentThread().getName()+",發(fā)起任務(wù)");
        new Thread(futureTask,"A").start();
        //分析入口
        final String s = futureTask.get();
        System.out.println("線程"+Thread.currentThread().getName()+",獲得結(jié)果,"+s);
    }
打印結(jié)果

開始分析FutureTask源碼,默認(rèn)你知道CAS,LockSupport。

  //分析入口
  final String s = futureTask.get();
 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);//進(jìn)入源碼
        return report(s);
    }
private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        //開啟死循環(huán)獲取數(shù)據(jù)
        for (;;) {
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            //4 線程執(zhí)行完畢,跳出循環(huán)
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)//1 第一次進(jìn)入創(chuàng)建 WaitNode
                q = new WaitNode();
            else if (!queued)
                //2 涉及到CAS自行腦補,waiters開始為null,與waitersOffset內(nèi)存地址的值比較,相同則為內(nèi)存地址waitersOffset值為q
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            else if (timed) {
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            else
                //3 此處獲取許可,阻塞
                LockSupport.park(this);
        }
    }
  • 標(biāo)注1:第一次進(jìn)入創(chuàng)建 WaitNode。
  • 標(biāo)注2:涉及到CAS自行腦補,waiters開始為null然后與waitersOffset內(nèi)存地址的值比較,相同,則為為內(nèi)存地址waitersOffset賦值為q。這點相當(dāng)重要。
  • 標(biāo)注3: 此處獲取許可,阻塞。
  • 標(biāo)注4:線程執(zhí)行完畢,跳出循環(huán)

在看看FutureTask實現(xiàn)Runnable的run方法源碼。

 public void run() {
        if (state != NEW ||
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                    //1  調(diào)用剛才Callable的call方法,在剛才列子中的。
                    result = c.call();
                   //2 執(zhí)行成功
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    setException(ex);
                }
                //3 繼續(xù)看下一個類
                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) {
        //4 修改 NEW狀態(tài)到 COMPLETING
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = v;
            UNSAFE.putOrderedInt(this, stateOffset, NORMAL); // final state
            //5 在看下面方法
            finishCompletion();
        }
    }
  private void finishCompletion() {
        // assert state > COMPLETING;
        //6  waiters此時不為空,在上面已經(jīng)分析
        for (WaitNode q; (q = waiters) != null;) {
          // 7 修改內(nèi)存地址的值waitersOffset 為null
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                for (;;) {
                    Thread t = q.thread;
                    if (t != null) {
                        q.thread = null;
                        //8 給調(diào)用get方法線程給一張允許票
                        LockSupport.unpark(t);
                    }
                    WaitNode next = q.next;
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }

        done();

        callable = null;        // to reduce footprint
    }
  • 標(biāo)注1 調(diào)用剛才Callable的call方法,在剛才列子中的。
  • 標(biāo)注2 方法執(zhí)行成功,沒有異常,用于后續(xù)處理。
  • 標(biāo)注3 進(jìn)入set方法。
  • 標(biāo)注4 修改 NEW狀態(tài)到 COMPLETING。
  • 標(biāo)注5 進(jìn)入finishCompletion方法。
  • 標(biāo)注6 waiters此時不為空,在上面已經(jīng)分析。
  • 標(biāo)注7 修改內(nèi)存地址的值waitersOffset 為null。
  • 標(biāo)注8 給調(diào)用get方法線程給一張允許票。get方法不在阻塞。
    對FutureTask源碼做了簡單分析,如有不對請指正。
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容