Search code examples
javaconcurrencyexecutor

How to interrupt executor thread


What the right way to interrupt executor's thread? I've got this: Thread class with name Worker with method:

public void run() {
    while(!(Thread.currentThread().isInterrupted()){
        System.out.println("work " + Thread.currentThread().getName() + ":" + Thread.currentThread().isInterrupted());
    }
}

And main class with:

ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
Worker worker = new Worker();                   
executorService.execute(worker);  

I try to call worker.interrupt(); or executorService.shutdownNow(); but my thread goes on and isInterrupted() is false.


Solution

  • Can you post all the relevant code? Based on the information you have given, I can't reproduce the behaviour you describe. See below a SSCCE that works as expected - output:

    work pool-1-thread-1:false
    work pool-1-thread-1:false
    work pool-1-thread-1:false
    ....
    Thread has been interrupted

    Code:

    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");
            }
        }
    }