java.util.concurrent.FutureTask 源码
2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
線程池相關(guān)
源碼:
package java.util.concurrent;import java.util.concurrent.locks.LockSupport;public class FutureTask<V> implements RunnableFuture<V> {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;private Callable<V> callable;private Object outcome;private volatile Thread runner;private volatile WaitNode waiters;static final class WaitNode {volatile Thread thread;volatile WaitNode next;WaitNode() {thread = Thread.currentThread();}}public FutureTask(Callable<V> callable) {if (callable == null)throw new NullPointerException();this.callable = callable;this.state = NEW;}public FutureTask(Runnable runnable, V result) {this.callable = Executors.callable(runnable, result);this.state = NEW;}public boolean isCancelled() {return state >= CANCELLED;}public boolean isDone() {return state != NEW;}public boolean cancel(boolean mayInterruptIfRunning) {if (!(state == NEW && UNSAFE.compareAndSwapInt(this, stateOffset, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED)))return false;try {if (mayInterruptIfRunning) {try {Thread t = runner;if (t != null)t.interrupt();} finally {UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED);}}} finally {finishCompletion();}return true;}public V get() throws InterruptedException, ExecutionException {int s = state;if (s <= COMPLETING)s = awaitDone(false, 0L);return report(s);}public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {if (unit == null)throw new NullPointerException();int s = state;if (s <= COMPLETING && (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)throw new TimeoutException();return report(s);}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 = null;int s = state;if (s >= INTERRUPTING)handlePossibleCancellationInterrupt(s);}}@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);}protected void done() {}protected void set(V v) {if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {outcome = v;UNSAFE.putOrderedInt(this, stateOffset, NORMAL);finishCompletion();}}protected void setException(Throwable t) {if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {outcome = t;UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL);finishCompletion();}}protected boolean runAndReset() {if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread()))return false;boolean ran = false;int s = state;try {Callable<V> c = callable;if (c != null && s == NEW) {try {c.call();ran = true;} catch (Throwable ex) {setException(ex);}}} finally {runner = null;s = state;if (s >= INTERRUPTING)handlePossibleCancellationInterrupt(s);}return ran && s == NEW;}private void handlePossibleCancellationInterrupt(int s) {if (s == INTERRUPTING)while (state == INTERRUPTING)Thread.yield();}private void finishCompletion() {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;q = next;}break;}}done();callable = null;}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)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);} elseLockSupport.park(this);}}private void removeWaiter(WaitNode node) {if (node != null) {node.thread = null;retry:for (; ; ) {for (WaitNode pred = null, q = waiters, s; q != null; q = s) {s = q.next;if (q.thread != null)pred = q;else if (pred != null) {pred.next = s;if (pred.thread == null)continue retry;} else if (!UNSAFE.compareAndSwapObject(this, waitersOffset, q, s))continue retry;}break;}}}// Unsafe方法private static final sun.misc.Unsafe UNSAFE;private static final long stateOffset;private static final long runnerOffset;private static final long waitersOffset;static {try {UNSAFE = sun.misc.Unsafe.getUnsafe();Class<?> k = FutureTask.class;stateOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("state"));runnerOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("runner"));waitersOffset = UNSAFE.objectFieldOffset(k.getDeclaredField("waiters"));} catch (Exception e) {throw new Error(e);}}}類 FutureTask<V>
????類型參數(shù):
????V?- 此 FutureTask 的?get?方法所返回的結(jié)果類型。
????所有已實(shí)現(xiàn)的接口:
????Runnable,?Future<V>,?RunnableFuture<V>
????可取消的異步計(jì)算。利用開始和取消計(jì)算的方法、查詢計(jì)算是否完成的方法和獲取計(jì)算結(jié)果的方法,此類提供了對(duì)?Future?的基本實(shí)現(xiàn)。
????僅在計(jì)算完成時(shí)才能獲取結(jié)果;如果計(jì)算尚未完成,則阻塞?get?方法。一旦計(jì)算完成,就不能再重新開始或取消計(jì)算。
????可使用?FutureTask?包裝?Callable?或?Runnable?對(duì)象。因?yàn)?FutureTask?實(shí)現(xiàn)了?Runnable,所以可將?FutureTask?提交給?Executor?執(zhí)行。
????除了作為一個(gè)獨(dú)立的類外,此類還提供了?protected?功能,這在創(chuàng)建自定義任務(wù)類時(shí)可能很有用。
?
構(gòu)造方法摘要
?
| FutureTask(Callable<V>?callable)? ??????????創(chuàng)建一個(gè)?FutureTask,一旦運(yùn)行就執(zhí)行給定的?Callable。 |
| FutureTask(Runnable?runnable,?V?result)? ??????????創(chuàng)建一個(gè)?FutureTask,一旦運(yùn)行就執(zhí)行給定的?Runnable,并安排成功完成時(shí)?get?返回給定的結(jié)果 。 |
?方法摘要
| ?boolean | cancel(boolean?mayInterruptIfRunning)? ??????????試圖取消對(duì)此任務(wù)的執(zhí)行。 |
| protected ?void | done()? ??????????當(dāng)此任務(wù)轉(zhuǎn)換到狀態(tài)?isDone(不管是正常地還是通過取消)時(shí),調(diào)用受保護(hù)的方法。 |
| ?V | get()? ??????????如有必要,等待計(jì)算完成,然后獲取其結(jié)果。 |
| ?V | get(long?timeout,?TimeUnit?unit)? ??????????如有必要,最多等待為使計(jì)算完成所給定的時(shí)間之后,獲取其結(jié)果(如果結(jié)果可用)。 |
| ?boolean | isCancelled()? ??????????如果在任務(wù)正常完成前將其取消,則返回?true。 |
| ?boolean | isDone()? ??????????如果任務(wù)已完成,則返回?true。 |
| ?void | run()? ??????????除非已將此 Future 取消,否則將其設(shè)置為其計(jì)算的結(jié)果。 |
| protected ?boolean | runAndReset()? ??????????執(zhí)行計(jì)算而不設(shè)置其結(jié)果,然后將此 Future 重置為初始狀態(tài),如果計(jì)算遇到異常或已取消,則該操作失敗。 |
| protected ?void | set(V?v)? ??????????除非已經(jīng)設(shè)置了此 Future 或已將其取消,否則將其結(jié)果設(shè)置為給定的值。 |
| protected ?void | setException(Throwable?t)? ??????????除非已經(jīng)設(shè)置了此 Future 或已將其取消,否則它將報(bào)告一個(gè)?ExecutionException,并將給定的 throwable 作為其原因。 |
?從類 java.lang.Object?繼承的方法
clone,?equals,?finalize,?getClass,?hashCode,?notify,?notifyAll,?toString,?wait,?wait,?wait
?
FutureTask
public FutureTask(Callable<V>?callable)????創(chuàng)建一個(gè)?FutureTask,一旦運(yùn)行就執(zhí)行給定的?Callable。
????參數(shù):
????callable?- 可調(diào)用的任務(wù)。
????拋出:
????NullPointerException?- 如果 callable 為 null。
?
FutureTask
public FutureTask(Runnable?runnable,V?result)????創(chuàng)建一個(gè)?FutureTask,一旦運(yùn)行就執(zhí)行給定的?Runnable,并安排成功完成時(shí)?get?返回給定的結(jié)果 。
????參數(shù):
????runnable?- 可運(yùn)行的任務(wù)。
????result?- 成功完成時(shí)要返回的結(jié)果。如果不需要特定的結(jié)果,則考慮使用下列形式的構(gòu)造:?Future<?> f = new FutureTask<Object>(runnable, null)
????拋出:
????NullPointerException?- 如果 runnable 為 null。
?
?
isCancelled
public boolean isCancelled()????從接口?Future?復(fù)制的描述
????????如果在任務(wù)正常完成前將其取消,則返回?true。
????指定者:
????????接口?Future<V>?中的?isCancelled
????返回:
????????如果任務(wù)完成前將其取消,則返回?true
?
?
isDone
public boolean isDone()????從接口?Future?復(fù)制的描述
????????如果任務(wù)已完成,則返回?true。 可能由于正常終止、異常或取消而完成,在所有這些情況中,此方法都將返回?true。
????指定者:
????????接口?Future<V>?中的?isDone
????返回:
????????如果任務(wù)已完成,則返回?true
?
?
cancel
public boolean cancel(boolean?mayInterruptIfRunning)????從接口?Future?復(fù)制的描述
????????試圖取消對(duì)此任務(wù)的執(zhí)行。如果任務(wù)已完成、或已取消,或者由于某些其他原因而無法取消,則此嘗試將失敗。當(dāng)調(diào)用?cancel?時(shí),如果調(diào)用成功,而此任務(wù)尚未啟動(dòng),則此任務(wù)將永不運(yùn)行。如果任務(wù)已經(jīng)啟動(dòng),則?mayInterruptIfRunning?參數(shù)確定是否應(yīng)該以試圖停止任務(wù)的方式來中斷執(zhí)行此任務(wù)的線程。
????此方法返回后,對(duì)?Future.isDone()?的后續(xù)調(diào)用將始終返回?true。如果此方法返回?true,則對(duì)?Future.isCancelled()?的后續(xù)調(diào)用將始終返回?true。
????指定者:
????????接口?Future<V>?中的?cancel
????參數(shù):
????mayInterruptIfRunning?- 如果應(yīng)該中斷執(zhí)行此任務(wù)的線程,則為?true;否則允許正在運(yùn)行的任務(wù)運(yùn)行完成
????返回:
????????如果無法取消任務(wù),則返回?false,這通常是由于它已經(jīng)正常完成;否則返回?true
?
get
public V get()throws InterruptedException,ExecutionException????從接口?Future?復(fù)制的描述
????????如有必要,等待計(jì)算完成,然后獲取其結(jié)果。
????指定者:
????????接口?Future<V>?中的?get
????返回:
????????計(jì)算的結(jié)果
????拋出:
????CancellationException?- 如果計(jì)算被取消
????InterruptedException?- 如果當(dāng)前的線程在等待時(shí)被中斷
????ExecutionException?- 如果計(jì)算拋出異常
?
get
public V get(long?timeout,TimeUnit?unit)throws InterruptedException,ExecutionException,TimeoutException????從接口?Future?復(fù)制的描述
????????如有必要,最多等待為使計(jì)算完成所給定的時(shí)間之后,獲取其結(jié)果(如果結(jié)果可用)。
????指定者:
????????接口?Future<V>?中的?get
????參數(shù):
????timeout?- 等待的最大時(shí)間
????unit?- timeout 參數(shù)的時(shí)間單位
????返回:
????????計(jì)算的結(jié)果
????拋出:
????CancellationException?- 如果計(jì)算被取消
????InterruptedException?- 如果當(dāng)前的線程在等待時(shí)被中斷
????ExecutionException?- 如果計(jì)算拋出異常
????TimeoutException?- 如果等待超時(shí)
?
?
done
protected void done()????當(dāng)此任務(wù)轉(zhuǎn)換到狀態(tài)?isDone(不管是正常地還是通過取消)時(shí),調(diào)用受保護(hù)的方法。默認(rèn)實(shí)現(xiàn)不執(zhí)行任何操作。子類可以重寫此方法,以調(diào)用完成回調(diào)或執(zhí)行簿記。注意,可以查詢此方法的實(shí)現(xiàn)內(nèi)的狀態(tài),從而確定是否已取消了此任務(wù)。
?
?
set
protected void set(V?v)????除非已經(jīng)設(shè)置了此 Future 或已將其取消,否則將其結(jié)果設(shè)置為給定的值。在計(jì)算成功完成時(shí)通過?run?方法內(nèi)部調(diào)用此方法。
????參數(shù):
????v?- 值
?
setException
protected void setException(Throwable?t)????除非已經(jīng)設(shè)置了此 Future 或已將其取消,否則它將報(bào)告一個(gè)?ExecutionException,并將給定的 throwable 作為其原因。在計(jì)算失敗時(shí)通過?run?方法內(nèi)部調(diào)用此方法。
????參數(shù):
????t?- 失敗的原因
?
?
run
public void run()????除非已將此 Future 取消,否則將其設(shè)置為其計(jì)算的結(jié)果。
????指定者:
????????接口?Runnable?中的?run
????指定者:
????????接口?RunnableFuture<V>?中的?run
????另請(qǐng)參見:
????Thread.run()
?
runAndReset
protected boolean runAndReset()????執(zhí)行計(jì)算而不設(shè)置其結(jié)果,然后將此 Future 重置為初始狀態(tài),如果計(jì)算遇到異常或已取消,則該操作失敗。本操作被設(shè)計(jì)用于那些本質(zhì)上要執(zhí)行多次的任務(wù)。
????返回:
????????如果成功運(yùn)行并重置,則返回 true。
轉(zhuǎn)載于:https://my.oschina.net/langwanghuangshifu/blog/2963574
總結(jié)
以上是生活随笔為你收集整理的java.util.concurrent.FutureTask 源码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: p2596 书架(Treap)
- 下一篇: node项目发送邮件失败