我观察到一个奇怪的现象,即提交任务后Thread.interruptted()
的值发生了变化,让我用代码来解释它。
package com.example;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;
public class TestClass {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 3,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()
, new ThreadFactoryBuilder().setNameFormat("ThreadTest-%d").build(),
new ThreadPoolExecutor.AbortPolicy()
);
Thread.currentThread().interrupt();
System.out.println("ThreadTest interrupted: " + Thread.interrupted());
Future<String> future;
future = threadPoolExecutor.submit(() -> {
System.out.println("running thread");
return "done";
});
System.out.println("ThreadTest interrupted: " + Thread.interrupted());
String s = future.get();
System.out.println("ThreadTest result: " + s);
}
}
运行它,我得到以下输出:
ThreadTest interrupted: true
ThreadTest interrupted: false
running thread
ThreadTest result: done
我的问题是,我已经中断了主线程,为什么在提交任务后它又变回不中断?是JDK中的错误吗?
我正在使用macOS,而我的Java版本如下:
java version "1.8.0_151"
Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.151-b12, mixed mode)
答案 0 :(得分:2)
https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html:
当线程通过调用静态方法检查中断时
Thread.interrupted
,中断状态已清除。
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupted():
该方法清除了线程的中断状态。
在问问题之前,请先阅读文档。