Friday, February 13, 2009

thread communication wait , notify , notifyall

Two threads can communicate with each other by using wait(), notify(), notifyall() methods Signatures.
Public final void wait() throw interepedException.
Public final native void wait(longms)throws InterruptedException.
Public final void wait(long ms,int ns)throws InterruptedException.
Public final native void notify();
Public final native void notifyAll();
Why this methods are in objclass instead of threadclass?
Wait(),notify();notifyAll() cantain in object class,not in the thread class.because these methods can be applied on common shared object,not on the thread.
Inorder to call wait(),notify(),notifyAll() on an object, we should be the owener of that object.
We are allowed to call wait(),notify(),notifyAll() methods from the synchronized context only(then only we will get the lock of that object and we will beome owner of that object )
If we call wait(),notify(),notifeAll() from non synchronized context,we will get a run time Exception saying”illegal monitar state Exception: not a owner”



If the thread call wait()method,first it releases the lock and thenit will go for waiting state, if the waiting thread gets ‘notification call’ or time expired’ or’got interruption’ then it will go for another blocked state for getting lock.
Once the thread got the lock, it will go to the ready state.
After calling wait method immedeatly releases the lock but after giving notify call the thread may not the lock immediately.
The only method which causes the releasing of lock is wait() method.
But in the case of sleep(),loin() or yield() the thread never releases the lock.
Method results release of lock:
Wait()
Join()
Sleep()
Yield()
Notify() // releases the lock, but may not immediatly
noifyAll()
A thread can acquire more then one lock at time .a thread releses the lock of an object on which it calls the wait()method .it run releses all the locks.
Example:
Class Thread A
{
Public static void main(string[]args)throws interrupted Exception
{
ThreadB b =new threadB();
b.start();
synchronized(b)//thread got lock
{
System.out.pritnln(“iam calling wait method”);
b.wait();
System.out.pritnlnpln(“I got notification);
}
System.out.pritnlnpln(b.total);
}
}
Class ThreadB extends Thread
{
Int total=0;
Public void run()
{
Synchronized (this).//.thread got lock
{
System.out.pritnln(“iam starting calculation”);
for(int i=0;i<=1000;i++)
{
Total=total+i;
}
System.out.pritnln(“iam giving notification call”);
notify();//thread releases lock again
}
}
} //500 500.
Flow -- > 0 -->1 --> 2 --> 3 --> 4 ---> 5

0 comments:

Post a Comment