中断执行程序线程的正确方法是什么? 我有这个: 名为Worker的线程类,方法:
public void run() {
while(!(Thread.currentThread().isInterrupted()){
System.out.println("work " + Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
}
}
主要课程:
ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
Worker worker = new Worker();
executorService.execute(worker);
我尝试调用worker.interrupt();
或executorService.shutdownNow();
,但我的线程继续,isInterrupted()为false。
答案 0 :(得分:1)
您可以发布所有相关代码吗?根据您提供的信息,我无法重现您描述的行为。请参阅下面的SSCCE按预期工作 - 输出:
work pool-1-thread-1:false
work pool-1-thread-1:false
work pool-1-thread-1:false
....
线程已被中断
代码:
public class Test {
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(1);
Worker worker = new Worker();
executorService.execute(worker);
executorService.shutdownNow();
}
public static class Worker extends Thread {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("work " + Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
}
System.out.println("Thread has been interrupted");
}
}
}