Java: How to wake thread on demand?
I think a combination of a BlockingQueue
and a ThreadPoolExecutor
will do what you need.
Or, if you deploy on a Java EE app server, you could use JMS and a message-driven bean.
I would use an ExecutorService like
private final ExecutorService executor = Executors.newSingleThreadExecutor();
public void task(final int arg) {
executor.execute(new Runnable() {
@Override
public void run() {
// perform task using `arg`
}
});
}
This has a built in thread which wakes when a tasks is added and sleeps when there is no tasks left, a Blocking Queue for queue tasks.
You can use some BlockingQueue
.
When you read from the queue (in the thread), you either get the next item, or if it is empty - wait until one is received.
This you are not actually sleeping the thread, but using the queue's blocking property. For example:
private BlockingQueue queue;
@Override
public void run() {
while(true) {
handle(queue.poll());
}
}
The above code is in a Runnable
- you can use an ExecutorService
to start a runnable, or the old-fashioned way with a Thread
The queue of course is set externally, and is filled (again externally) with the incoming items.