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.
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With