我在ThreadPoolExecutor $ Worker.runTask中发现了这样奇怪的代码

if (runState < STOP && Thread.interrupted() && runState >= STOP)
                thread.interrupt();

为什么需要检查runState < STOPrunState >= STOP
有一条评论以某种方式解释了为什么需要这种双重检查的原因,但我不理解。

因此,要计算表达式的最终值,它将从内存runState中获取,然后调用Thread.interrupted(),然后再次从内存runState中获取(第一个runState可能与第二个runState不同?),并将这三个表达式的值与and?

最佳答案

该代码的最初目的是清除线程的interrupted状态,除非它是shuttingDownNow,所以它只能是

if (runState < STOP)
      Thread.interrupted();

但是我们有并发性。考虑两个线程运行代码Worker:
if (runState < STOP &&
      Thread.interrupted() &&
      runState >= STOP)
    thread.interrupt();

和执行shutdownNow的线程:
if (state < STOP)
    runState = STOP;
for (Worker w : workers) {
    w.interruptNow();
}

现在是这种双重检查的情况
Worker:        if (runState < STOP &&    // true for now

shutdownNow:   if (state < STOP)
shutdownNow:       runState = STOP;      // set new state
shutdownNow:   for (Worker w : workers) {
shutdownNow:       w.interruptNow();     // interrupt
shutdownNow:   }

Worker:              Thread.interrupted() &&   // clears interrupted state
Worker:              runState >= STOP)         // but we have double check
Worker:            thread.interrupt();         // that will setup it again

10-07 23:33