Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a thread sleep from another thread in Java

I have two threads of execution(say Thread1 and Thread2). Thread2 is listening for a particular event and as the event occurs it wants to stop execution of Thread1 and trigger an action. After it is done with the action it needs to continue the execution of Thread1 from where it stopped.

What kind of approach should I take to do this in Java?

like image 735
asthiwanka Avatar asked Jun 28 '11 12:06

asthiwanka


1 Answers

The clean way to do it, IMHO, is to make Thread1 regularly poll some state variable to see if it has been asked to pause. If it's been asked to pause, then it should suspend its execution, waiting for some lock to be released.

Thread2 should ask Thread1 to pause by changing the value of the shared state variable, then potentialy wait for Thread1 to accept the pause request, then execute its action and release the lock on which Thread1 is waiting.

In short, the two threads must collaborate. There is no way that I'm aware of to pause a thread cleanly without its collaboration.

like image 154
JB Nizet Avatar answered Oct 06 '22 01:10

JB Nizet