Search

Friday, April 16, 2010

What methods are responsible for inter thread communication

Following Three Methods are responsible for inter thread communication :

1. wait()
2. notify()
3. notifyAll()

These methods are part of Object class. And should always called within Synchronized block .

Let us understand from following example : 

class Operator extends Thread {
public void run(){
while(true){
// Get shape from user
synchronized(this){ // lock the same object
// Calculate new machine steps from shape // finish the work
notify(); // notify the waiting thread i.e Machine thread
}
}
}
}
class Machine extends Thread {
Operator operator; // assume this gets initialized
public void run(){
while(true){
synchronized(operator){ // lock on the operator object
try {
operator.wait(); // waiting for notification from operator object , once notify will call
} catch(InterruptedException ie) {}
// Send machine steps to hardware
}
}
}
}
The machine thread, once started, will immediately go into the waiting state and
will wait patiently until the operator sends the first notification.

Note : When the wait() method is invoked on an object, the thread executing
that code gives up its lock on the object immediately. However, when
notify() is called, that doesn’t mean the thread gives up its lock at that
moment. If the thread is still completing synchronized code, the lock is not
released until the thread moves out of synchronized code. So just because
notify() is called doesn’t mean the lock becomes available at that moment.

No comments:

Post a Comment