1

中断执行者线程的正确方法是什么?我有这个:名称为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() 是错误的。

4

1 回答 1

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");
        }
    }
}
于 2012-06-24T08:59:50.490 回答