1

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.

user1406196
  • 147
  • 3
  • 12
  • Check this out which might be a possible duplicate http://stackoverflow.com/questions/7142665/why-does-thread-isinterrupted-always-return-false – GETah Jun 23 '12 at 20:34

1 Answers1

1

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");
        }
    }
}
assylias
  • 321,522
  • 82
  • 660
  • 783
  • Thank you for the answer. Your code is work fine, the difference from mine, that in Worker class in run method I work with JMS. Just one line `messageService.sendMessage(message);` If i comment it, thread stops, if not its always `work pool-1-thread-1:false`. And I can stop thread just with my own flag instead of isInterrupted() – user1406196 Jun 24 '12 at 09:59