Java Wake Sleeping Thread

James Oravec picture James Oravec · Jun 9, 2014 · Viewed 19.5k times · Source

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?

Answer

Patricia Shanahan picture Patricia Shanahan · Jun 9, 2014

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