Java Multitasking  «Prev  Next»

Lesson 8Using wait() and notify()
Objective Be able to use wait() and notify() in your own application

Using wait() and notify() with JavaThreads

For the town hall meeting, the MC allows utterances to be heard by taking them from the podium one at a time.
To implement this, the MC sometimes has to wait until one of the speakers says something. The ability to make a thread wait on some condition is a powerful feature of Java, and we will explore it in this section.
First, we will look at the MC's run() method.
Then, we will look at where the MC waits for something to be said.
Then, we will see how the participants notify them when they have said something.
Match the method with the class names in which they are defined;
Method Name:Class Name: [java.lang.Object, java.lang.Thread, NONE]
joinjava.lang.Thread
lock NONE (Lock is an interface)
notify java.lang.Object
releaseNONE
run java.lang.Thread
sleep java.lang.Thread
startjava.lang.Thread
synchronize NONE
waitjava.lang.Object

synchronized keyword

synchronized is a keyword that is used to get a lock on an object. It is not a method.There are no such methods as lock and release in the Object or Thread classes. However, there is a lock() method in java.util.concurrent.locks.Lock interface. synchronized acquires the lock, Object's wait() is used to wait on object, and Object's notify/notifyAll methods are used to release a lock.
For example,
synchronized(myObj){  //acquire a lock on myObj
 obj.wait();          // line 2
}
synchronized(myObj){  // acquire a lock on myObj
 obj.notifyAll();     // line 5
} 

line 2: release the acquired lock and wait for a call to notify or notifyAll() by some other thread on the same object.
line 5: notify all other threads who have called myObj.wait(). Unlike wait(), lock is not actually released by notify()/notifyAll(). Lock is released at the end of the synchronized block.
When you have a good overview of multitasking, take the quiz.
Thread States - Quiz