中断执行器线程的正确方法是什么? 我有这个: 名为 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。
最佳答案
您可以发布所有相关代码吗?根据您提供的信息,我无法重现您所描述的行为。请参阅下面的SSCCE按预期工作 - 输出:
work pool-1-thread-1:false
work pool-1-thread-1:false
work pool-1-thread-1:false
....
Thread has been interrupted
代码:
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");
}
}
}
关于java - 如何中断执行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11172523/