if we call the wait() of object a :
a.wait() ---> this will block the thread and release the lock of a
if we call the notify() of object a :
a.notify() --> will disblock one of the blocked threads (randomly)
1 > If we use the synchronized we don't have to use wait()/notify()
2 > If we use the wait()/notify() we have to use synchronized :
( wait/notify should be in synchronized)
we can find wait()/notify() is not from the thread part, it's from class Object!
ex : transaction of an bank account :
public class Bank{
float account[ACCOUNT_NUM];
..............
public synchronized void transfer(int from, int to, float amount){
while( account[from] < amount){
wait();
}
account[from] -=amount;
account[to] +=amount;
notifyAll();
}
}
use while() rather than if, we can do the loop
use notifyAll() is better than notify()
No comments:
Post a Comment