Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to signal other thread to stop?

Tags:

java

Started several worker threads , need to notify them to stop. Since some of the threads will sleep for a while before next round of working, need a way which can notify them even when they are sleeping.

If it was Windows programming I could use Event and wait functions. In Java I am doing this by using a CountDownLatch object which count is 1. It works but don't feel elegant, especially I have to check the count value to see if need to exit :

run(){
    while(countDownLatch.count()>0){
            //working
            // ...
            countDownLatch.wait(60,TimeUnit.SECONDS);
    }
}

Semaphore is another choice, but also don't feel very right. I am wondering is there any better way to do this? Thank you.

like image 817
HourseArmor Avatar asked Jul 28 '11 13:07

HourseArmor


1 Answers

Best approach is to interrupt() the worker thread.


Thread t = new Thread(new Runnable(){
    @Override
    public void run(){
        while(!Thread.currentThread().isInterrupted()){
            //do stuff
            try{
                Thread.sleep(TIME_TO_SLEEP);
            }catch(InterruptedException e){
                Thread.currentThread().interrupt(); //propagate interrupt
            }
        }
    }
});
t.start();

And as long as you have a reference to t, all that is required to "stop" t is to invoke t.interrupt().

like image 143
Moonbeam Avatar answered Nov 15 '22 16:11

Moonbeam