上次總結一下AQS的一些相關知識,這次總結了一下FutureTask的東西,相對于AQS來說簡單好多呀
之前提到過一個LockSupport的工具類,也了解一下這個工具類的用法,這里也鞏固一下吧
/*** Makes available the permit for the given thread, if it* was not already available. If the thread was blocked on* {@code park} then it will unblock. Otherwise, its next call* to {@code park} is guaranteed not to block. This operation* is not guaranteed to have any effect at all if the given* thread has not been started.** @param thread the thread to unpark, or {@code null}, in which case* this operation has no effect*///將指定線程喚醒,繼續執行指定線程public static void unpark(Thread thread) {if (thread != null)UNSAFE.unpark(thread);} /*** Disables the current thread for thread scheduling purposes unless the* permit is available.** <p>If the permit is available then it is consumed and the call* returns immediately; otherwise the current thread becomes disabled* for thread scheduling purposes and lies dormant until one of three* things happens:** <ul>** <li>Some other thread invokes {@link #unpark unpark} with the* current thread as the target; or** <li>Some other thread {@linkplain Thread#interrupt interrupts}* the current thread; or** <li>The call spuriously (that is, for no reason) returns.* </ul>** <p>This method does <em>not</em> report which of these caused the* method to return. Callers should re-check the conditions which caused* the thread to park in the first place. Callers may also determine,* for example, the interrupt status of the thread upon return.*///阻塞當前線程,等待調用unpark()喚醒當前線程public static void park() {UNSAFE.park(false, 0L);}// Hotspot implementation via intrinsics APIprivate static final sun.misc.Unsafe UNSAFE;
就是阻塞線程以及喚醒指定線程,在FutureTask的源碼中能用到
RunnableFuture<V>
FutureTask繼承自這個接口,這個接口有繼承了Runnable以及Future接口,所以FutureTask對象可以用new?Thread().start()去啟動,所以之前提到了創建線程的三種方式,采用Callable+FutureTask的形式創建,依舊還是依賴于Runnable創建線程
/*** A {@link Future} that is {@link Runnable}. Successful execution of* the {@code run} method causes completion of the {@code Future}* and allows access to its results.* @see FutureTask* @see Executor* @since 1.6* @author Doug Lea* @param <V> The result type returned by this Future's {@code get} method*/
public interface RunnableFuture<V> extends Runnable, Future<V> {/*** Sets this Future to the result of its computation* unless it has been cancelled.*/void run();
}
源碼解析
既然繼承了Runnable接口就必然執行run()方法,我們先看下主要成員變量
/*** 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;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;/** The underlying callable; nulled out after running *///Callable對象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;//單向鏈表static final class WaitNode {volatile Thread thread;//記錄當前線程volatile WaitNode next;//下一個節點WaitNode() { thread = Thread.currentThread(); }}
看一下執行主體,這個方法主要是將Callable對象的那個業務邏輯執行完畢,只有執行完成之后采用將值返回,并且將當前線程通過LockSupport.unpark()進行喚醒。
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();//調用Callable對象并執行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);}}/*** Removes and signals all waiting threads, invokes done(), and* nulls out callable.*///無論結果是否正常,都會執行,主要是為了喚醒線程,避免死鎖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 gcq = next;}break;}}done();callable = null; // to reduce footprint}
看一下Future的結果值的方法,每步方法在代碼中都有講解
/*** @throws CancellationException {@inheritDoc}*/public V get() throws InterruptedException, ExecutionException {int s = state;//先判斷當前線程的執行狀態是否執行完畢,未執行完的則調用等待方法if (s <= COMPLETING)s = awaitDone(false, 0L);return report(s);}/*** Awaits completion or aborts on interrupt or timeout.** @param timed true if use timed waits* @param nanos time to wait, if timed* @return state upon completion*///方法就是用過LockSupport.park()進入線程等待方法,等待調用unpark然后在次判斷是否執行完,執行完后將改方法結束,進入下一階段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 yetThread.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);}elseLockSupport.park(this);}}/*** Returns result or throws exception for completed task.** @param s completed state value*/@SuppressWarnings("unchecked")//在等待完之后,再次判斷是否正常完成執行,正常的話將值返回,否則拋出異常private V report(int s) throws ExecutionException {Object x = outcome;if (s == NORMAL)return (V)x;if (s >= CANCELLED)throw new CancellationException();throw new ExecutionException((Throwable)x);}
通過上面的講解,應該對FutureTask為什么能有返回值以及基本運行機制應該有個初步的了解,可以自行的去多看幾遍。