Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: How to wake thread on demand?

Let's say I want to create an object that basically runs a thread infinitely. I want the thread to sleep while there is no need for him, but when there is a need for certain job to be done, it wakes the thread - gets the job done and goes back to sleep. I also want the jobs to be queued and be executed in the order they arrive. In cocoa/objective c there is an NSOperationQueue for that. I wonder if java has something similar.

What do you think?

like image 880
Alex1987 Avatar asked May 27 '11 10:05

Alex1987


People also ask

How do you wake up a sleeping thread?

Waking up Wait and Sleep We can wake the thread by calling either the notify() or notifyAll() methods on the monitor that is being waited on. Use notifyAll() instead of notify() when you want to wake all threads that are in the waiting state.

Which method is used to wake up another thread?

1) The Thread. sleep() is a static method and it always puts the current thread to sleep. 2) You can wake-up a sleeping thread by calling the interrupt() method on the thread which is sleeping.

What happens when thread's sleep () method is called?

Thread. sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system.

How do you make a thread wait for some time?

So, when wait() method is called by a thread, then it gives up the lock on that resource and goes to sleep until some other thread enters the same monitor and invokes the notify() or notifyAll() method. Calling notify() wakes only one thread and calling notifyAll() wakes up all the threads on the same object.


2 Answers

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.

like image 167
Peter Lawrey Avatar answered Oct 31 '22 10:10

Peter Lawrey


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.

like image 25
duffymo Avatar answered Oct 31 '22 11:10

duffymo