Is there standard implementation for thread block/resume in java SE?

134 Views Asked by At

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.

4

There are 4 best solutions below

0
On BEST ANSWER

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 count 1: 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.

0
On

have a a look at the classes in java.util.conucurrent ... CountDownLatch might be a solution for your problem if i understand your problem correctly.

2
On

using an ExecutorService and calling invokeAll might also be an option.

http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html

this way lets you also specify a timeout in which all tasks should have been finished. Which is generally a very good idea, if you want to have a responsive application.

1
On

I need to block execution of a thread until resumed from another thread.

Not enough information. Do you need an on/off switch that is controlled entirely by one thread and obeyed by the other? That might be a good application for a Turnstile: Pause thread from another thread(s) and also stop/start it yet from another thread

Or do you need "one-shot" behavior? (i.e., the "background" thread does one thing each time the "foreground" thread gives it permission to go.) That would be a good application for a java.util.concurrent.Semaphore.

Or, do you need some other behavior?