privatevolatileint state;privatestaticfinalint NEW =0;privatestaticfinalint COMPLETING =1;privatestaticfinalint NORMAL =2;privatestaticfinalint EXCEPTIONAL =3;privatestaticfinalint CANCELLED =4;privatestaticfinalint INTERRUPTING =5;privatestaticfinalint INTERRUPTED =6;
state 属性是整个 FutureTask 的核心属性,它代表了任务在运行过程中的状态,随着任务的执行,状态将不断地进行转变;任务的起始状态都是 NEW,中间状态为 COMPLETING / INTERRUPTING,其他为终止状态;任务的中间状态是一个瞬态,它非常的短暂,而且任务的中间态并不代表任务正在执行,而是任务已经执行完了,正在设置最终的返回结果,所以只要state不处于 NEW 状态,就说明任务已经执行完毕。
privatevoidfinishCompletion() {// 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}
run()
// 一般是由线程池中的线程来执行publicvoidrun() {// 任务在线程池中执行时,状态必须是 NEW// 如果存在多线程竞争执行一个任务,只有竞争成功的才可以去执行任务,这里是通过 CAS 操作实现的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 interruptsint s = state;if (s >= INTERRUPTING)handlePossibleCancellationInterrupt(s); }}