Java異步Future詳解

簡介

Future主要用於有返回值的異步任務。最核心的類是FutureTask,它是Future接口唯一的實現類。

FutureTask

這裏寫圖片描述
可以看出FutureTask類實現了Runnable和Future接口。
內部屬性有

    private volatile int state;
    private Callable<V> callable;
    /** The result to return or exception to throw from get() */
    private Object outcome; // non-volatile, protected by state reads/writes
    /** The thread running the callable; CASed during run() */
    private volatile Thread runner;
    /** Treiber stack of waiting threads */
    private volatile WaitNode waiters;

其中

  • state表示任務執行狀態,有下面幾個取值
    private static final int NEW = 0;
    private static final int COMPLETING = 1;
    private static final int NORMAL = 2;
    private static final int EXCEPTIONAL = 3;
    private static final int CANCELLED = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED = 6;
  • callable是實際要執行的run方法的對象
  • outCome是執行的結果
  • runner是執行run方法的線程
  • waitNodes是一個鏈表,存儲調用get或者別的方法而阻塞的線程

構造函數

有兩週構造函數,分別傳入Runnable對象和Callable對象

 public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
 public FutureTask(Runnable runnable, V result) {
        this.callable = Executors.callable(runnable, result);
        this.state = NEW;       // ensure visibility of callable
    }

當傳入構造函數的對象是Runnable時,調用Executors.callable(Runnable,Result)方法返回一個callable的適配器,這個適配器的call方法會調用runnable的run方法,並固定返回傳入的result對象。

run方法

在run方法調用callable的call方法,並把返回結果賦值給outcome屬性。

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 {
                    result = c.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);
        }
    }

get方法

用於獲取執行的結果,如果沒有執行完則阻塞等待,可以設置超時時間。

 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

awaitDone方法

在get方法中調用awaitDone方法阻塞等待。awaitDone方法會把當前調用get的線程yield掛起並放在一個鏈表中,執行完成之後會一一喚醒

private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        for (;;) {
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            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)
                q = new WaitNode();
            else if (!queued)
                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
                LockSupport.park(this);
        }
    }

finishCompletion執行完成調用

 private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, 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();
callable = null;        // to reduce footprint
    }

使用方法

可以直接使用callable或者包裝成FutureTask

public static void main(String[] args) throws ExecutionException, InterruptedException {
        /**
         * 使用FutureTask
         */
        //      FutureTask<String> futureTask=new FutureTask<String>(new MyTask());
//      ExecutorService myExecuterservice = Executors.newFixedThreadPool(2);
//      myExecuterservice.submit(futureTask);
//      myExecuterservice.shutdown();
//      System.out.println(futureTask.get());

        /**
         * 直接使用callable
         */

        ExecutorService myExecutorService = Executors.newFixedThreadPool(2);
        Future<String> future = myExecutorService.submit(new MyTask());
        System.out.println(future.get());
        myExecutorService.shutdown();


    }
    }

  class MyTask implements Callable<String>{
    public String call(){
        System.out.println("call begins...");
        try {
            Thread.sleep(1000l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "Hello from mytask!";
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章