Producer & Consumer with Java wait(), notify() and notifyAll() | Now Now Now
Java Thread: notify() and wait() examples
How to Work With wait(), notify() and notifyAll() in Java?
1. Keywords & Methods:
- Synchronized
synchronized
keyword is used for exclusive accessing.- To make a method synchronized, simply add the synchronized keyword to its declaration. Then no two invocations of synchronized methods on the same object can interleave with each other.
- wait()
- Tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().
General syntax for callingwait()
method is like this:123456synchronized
(lockObject){
while
(!condition) {
lockObject.wait();
}
//take the action here;
}
- Tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().
- notify()
- Wakes up the first thread that called
wait()
on the same object. It should be noted that callingnotify()
does not actually give up a lock on a resource. It tells a waiting thread that that thread can wake up. However, the lock is not actually given up until the notifier's synchronized block has completed. So, if a notifier callsnotify()
on a resource but the notifier still needs to perform 10 seconds of actions on the resource within its synchronized block, the thread that had been waiting will need to wait at least another additional 10 seconds for the notifier to release the lock on the object, even thoughnotify()
had been called.123456789synchronized
(lockObject)
{
//establish_the_condition;
lockObject.notify();
//any additional code if needed
}
//lock is given up after synchronized block is ended
- Wakes up the first thread that called
- notifyAll()
- Wakes up all threads that are waiting on this object's monitor. The highest priority thread will run first in most of the situation, though not guaranteed. Other things are same as
notify()
method above.
- Wakes up all threads that are waiting on this object's monitor. The highest priority thread will run first in most of the situation, though not guaranteed. Other things are same as
Read full article from Producer & Consumer with Java wait(), notify() and notifyAll() | Now Now Now
No comments:
Post a Comment