FutureTask相关 (2)

在执行结束时,看到finally里还有段逻辑

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); } private void handlePossibleCancellationInterrupt(int s) { // It is possible for our interrupter to stall before getting a // chance to interrupt us. Let's spin-wait patiently. if (s == INTERRUPTING) while (state == INTERRUPTING) Thread.yield(); // wait out pending interrupt // assert state == INTERRUPTED; // We want to clear any interrupt we may have received from // cancel(true). However, it is permissible to use interrupts // as an independent mechanism for a task to communicate with // its caller, and there is no way to clear only the // cancellation interrupt. // // Thread.interrupted(); }

这是在干嘛呢,是因为,即使我们在上一步通过set或者setException设置了当前task的状态,但可能有别的线程在通过调用cancel来设置当前task的状态,如果有的话,这里就自旋空转,直到cancel方法执行结束。

那cancel方法是怎么工作的呢

public boolean cancel(boolean mayInterruptIfRunning) { if (!(state == NEW && UNSAFE.compareAndSwapInt(this, stateOffset, NEW, mayInterruptIfRunning ? INTERRUPTING : CANCELLED))) return false; try { // in case call to interrupt throws exception if (mayInterruptIfRunning) { try { Thread t = runner; if (t != null) t.interrupt(); } finally { // final state UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); } } } finally { finishCompletion(); } return true; }

cancel方法其实就是通过找到执行当前task的runner,然后调用thread的interrupt方法,这里需要注意的是,thread.interrupt方法仅仅是设置一个标志位,具体线程有没有响应,要看自己的实现。反正这里就是调一把interrupt然后就走了,然后通知所有watch的线程。

watch的线程,通过get方法获得执行结果是怎么拿到的呢

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 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); } }

核心逻辑就是,先把自己这个线程放到watch的waitNodes栈中,然后park 等待,直到task的状态>COMPLETING.

reference

https://segmentfault.com/a/1190000016572591

https://segmentfault.com/a/1190000016542779

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zysfxg.html