/** * 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 */ privatevolatileint state; privatestaticfinalint NEW = 0; privatestaticfinalint COMPLETING = 1; privatestaticfinalint NORMAL = 2; privatestaticfinalint EXCEPTIONAL = 3; privatestaticfinalint CANCELLED = 4; privatestaticfinalint INTERRUPTING = 5; privatestaticfinalint INTERRUPTED = 6;
这是当前任务的执行过程中的状态。可能的状态转化为:
1 2 3 4
* NEW -> COMPLETING -> NORMAL * NEW -> COMPLETING -> EXCEPTIONAL * NEW -> CANCELLED * NEW -> INTERRUPTING -> INTERRUPTED
也就是说,初始的状态是 NEW ,COMPLETING , INTERRUPTING 是里面的中间过渡状态,其他的都是 终止状态。
状态的改变
看这张图:
状态的改变只有三个: cancel , set , setException 。 在注释中也提到了,在我们的这个执行的过程中,我们的这个状态可以被 set , 从而中断了原来的执行。
@SuppressWarnings("unchecked") private V report(int s)throws ExecutionException { Object x = outcome; if (s == NORMAL) return (V)x; if (s >= CANCELLED) thrownew CancellationException(); thrownew ExecutionException((Throwable)x); }
publicvoidrun(){ 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); } }