如果你暴露线程执行程序让你运行,那么你可以打断它。对我来说,这只打印14次表明中断成功。
请记住,这依赖于一个事实,即Thread.sleep和System.out.println是中断的。如果你没有检查Thread.isInterrupted(就像他们两个那样),你仍然可能无法中断线程。ExecutorService executor = Executors.newSingleThreadExecutor();private void test() throws InterruptedException {
AtomicReference thread = new AtomicReference<>();
Future task = executor.submit(() -> {
// Keep track of the thread.
thread.set(Thread.currentThread());
try {
while (true) {
Thread.sleep(1000);
System.out.println("1");
}
} finally {
System.out.println("Interrupted: " + Thread.currentThread().isInterrupted());
}
});
Thread.sleep(5000);
// Interrupt the thread.
thread.get().interrupt();
Thread.sleep(5000);
System.out.println("Press to shutdown");
new Scanner(System.in).nextLine();
executor.shutdown();
System.out.println("Press to shutdown NOW");
new Scanner(System.in).nextLine();
executor.shutdownNow();}