I need to block execution of a thread until resumed from another thread. So I wrote my own implementation using wait()
method. Which seems to be working, but it is far from simple.
Is there any ready to use solution? Preferably in java SE 6? Or do I have to use my own implementation? I couldn't find any.
Update More specifically. I need work->block->external release->work->end behavior from thread 1 and ability to release block from thread 2.
Inspired by other answers, I found two solutions:
First:
Create
Semaphore
with no (0
) permits:Semaphore semaphore = new Semaphore(0);
in first thread. And share reference to it with your second thread.Do some work in the first thread and call
semaphore.acquire();
when you wish to stop execution.Some time later call
semaphore.release();
from second thread to unblock the first one.Second:
Create
CountDownLatch
with initial count1
:CountDownLatch countDownLatch = new CountDownLatch (1);
And again, share reference to it with both threads.Call
countDownLatch.await();
when you wish to block execution of the first thread.The first thread can be resumed by calling
countDownLatch.countDown();
somewhere in the second thread.