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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With