Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Wake Sleeping Thread

I did some reading of other post but didn't find an exact answer to what I'm looking for, so I hope someone can give some some clarification.

I have a program that will run for some time. I have some threads that run in the back ground that perform various tasks, to keep things simple let think of 3 threads. ThreadA performs a task every 10 seconds, where ThreadB does something every 30 seconds and ThreadC does something every 5 mintues.

I don't use busy waiting, and put the threads to sleep for the designated times.

My question is regarding a clean shut down. I have a variable that each of the threads have read access too, so they can see when the user initiates the exit of the program. The next time the threads are active, they exit their loops and join and all is good. But you can see that ThreadC only wakes up every 5 minutes.

The question I have is can I signal the sleeping threads to wake up and exit before their sleep time is over? If this is not possible, do I need to rework the code to use wait() and notify() or is there a better way?

like image 838
James Oravec Avatar asked Jun 08 '14 22:06

James Oravec


1 Answers

Thread.sleep throws InterruptedException if the thread is interrupted during the sleep. Catch that, and check your flag.

like image 155
Patricia Shanahan Avatar answered Oct 13 '22 00:10

Patricia Shanahan