1. 程式人生 > >JAVA併發程式設計:Future

JAVA併發程式設計:Future

生活

在水中行走,和根據一份需求開發軟體一樣,如果它們都 “凍” 住了,那就容易多了。

前言

前面學習了ThreadPoolExecutor,還學習了大神們提供的預先設定好的三個ThreadPoolExecutor,使得我們能更加方便得使用執行緒池。
在使用執行緒池的時候,有一些情況不需要返回返回值,但是也有很大情況要求返回執行緒執行的結果,比如一個操作是成功還是失敗。因此我們需要提交執行緒到執行緒池,並且得到返回結果。
先來看下下面三個介面

Runnable

public interface Runnable {
    public abstract void run();
}

大家知道常規建立執行緒的方式有兩種,一種是繼承Thread,重寫run,另一個是用Thread包裝一個Runnable的實現類,注意這兩種方式來建立執行緒都無法獲取到執行緒的返回結果,同樣,提交到執行緒池,如果用返回結果的物件來接受,得到的result自然也是null。

Callable

public interface Callable<V> {
    V call() throws Exception;
}

Callable的call方法存在返回值,即可以返回執行緒執行的結果,它通常和執行緒池一起使用

Future

public interface Future<V> {

  //取消執行緒執行,設定為false,則不允許線上程執行時中斷
    boolean cancel(boolean mayInterruptIfRunning);

 //是否取消成功
    boolean isCancelled();
//是否執行成功
    boolean isDone();
//阻塞獲取執行結果
    V get() throws InterruptedException, ExecutionException;
//阻塞超時獲取執行結果
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}

Future物件就是執行緒池給出的,允許檢視執行緒執行情況,中斷執行緒,並獲取執行緒返回值的物件。

程式碼示例

下面來看一下通過Future獲取執行緒返回結果的案例,注意,要返回結果,那麼必須選擇入參是Callable的提交方法。

		ExecutorService service = Executors.newCachedThreadPool();
		Future<String> future = service.submit(new Callable<String>() {

			@Override
			public String call() throws Exception {
				System.out.println("執行成功");
				return "success";
			}
		});
		System.out.println("result:"+future.get());

下面來看下提交的流程:

submit裡的方法

 public <T> Future<T> submit(Callable<T> task) {
        if (task == null) throw new NullPointerException();
        //封裝成一個RunnableFuture物件
        RunnableFuture<T> ftask = newTaskFor(task);
        //執行,最終呼叫到ftask的run方法
        execute(ftask);
        return ftask;
    }
  protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
        return new FutureTask<T>(callable);
    }

 

來看下 FutureTask是個什麼鬼?

//FutureTask實現了RunnableFuture介面
public class FutureTask<V> implements RunnableFuture<V>{
//構造器傳入callable物件,賦值給一個成員變數,並設定state
 public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }
}

//RunnableFuture介面又繼承了Runnable,Future,因此他既能執行一個執行緒,又能得到執行緒的狀態、返回值以及實現中斷等
public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
     //這裡不太明白的一點是 Runnable裡明明有run,為什麼這個多此一舉在寫一遍?
    void run();
}

我們得知執行緒池的execute方法最終呼叫到傳入的Runnable物件的run方法,
這裡通過submit封裝callable並傳入的FutureTask物件也是Runnable的物件,因此,最終會呼叫到FutureTask的run方法,因此這裡需要研究這個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 {
                //執行獲取返回值
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    
                    setException(ex);
                }
                if (ran)
                //設定結果 ,這裡設定給了outcome,因此FutureTask的get方法必然會去獲取outcome
                    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);
        }
    }
//賦值完成呼叫 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
    }

好,下面來看下get,是不是真的如我所料?

 public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
        //當s<=COMPLETING 可以還沒有賦值,需要阻塞一會
            s = awaitDone(false, 0L);
            //返回結果 就是outcome
        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;
        for (;;) {
            if (Thread.interrupted()) {
                removeWaiter(q);
                throw new InterruptedException();
            }

            int s = state;
            //如果>COMPLATING,要麼就執行完,要麼就取消或者異常,到report裡面去操作就行了
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            //如果是COMPLETING,說明執行完,正要賦值,讓個步就行了
            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);
        }
    }

注意:上面的程式碼裡面經常拿state說事,所以這裡也有必要把state的各種狀態瞭解一下。
FutureTask內建一個被volatile修飾的state變數。
按照生命週期的階段可以分為:

NEW 初始狀態
COMPLETING 任務已經執行完(正常或者異常),準備賦值結果
NORMAL 任務已經正常執行完,並已將任務返回值賦值到結果
EXCEPTIONAL 任務執行失敗,並將異常賦值到結果
CANCELLED 取消
INTERRUPTING 準備嘗試中斷執行任務的執行緒
INTERRUPTED 對執行任務的執行緒進行中斷(未必中斷到)

關於FutureTask的弊端,有的部落格裡寫道了,但我還不是很明白,先貼出來記錄一下!
https://www.cnblogs.com/micrari/p/7374513.html