您的位置:首页 > 编程语言 > Java开发

Java同步机制之notify vs notifyAll

2009-01-20 15:16 429 查看
use the wait-and-notify mechanism to deal with synchronized accessing a resource

wait-and-notify mechanism
1 wait & notify can never be out of synchronized block of the releated-object (wait和notify方法必须在与之对应的对象的同步块里调用)
2 wait can release & get the lock automatically

the difference between notify and notifyAll
1 notify is wake the thread which invoke the wait-method
2 notifyAll is wake all the thread waiting for the lock released
3 why can form the thread invoking the wait-method and threads waiting for the lock released?
we know, if a synchronized method is invoked, all the other synchronized methods belong to the object can not be invoked, so the invoking threads must be blocked, and waiting the method can be invoke, so they all waite for the lock released in the list of waiting queue.
a synchronized class is the same;
when the notify method occurs, the waiting one who invoked wait() be wake;
when the notifyAll method occurs, the waiting queue choose the most prior one to wake, can be the one invoking wait(), also can be the ones waiting the lock released;

what we should be care?
if one waiting thread is waked, its waiting condition may not be satisfied. and in the right way, it should wait continuely.
how we assure this route?
--just as follows came from <Effective Java> and <Practical Java>
the former: Never invoke wait outside a loop
eg:

1



synchronized(obj) {
2



while(<condition does not hold>) {
3

wait();
4

// Perform action appropriate to condition
5

}
6

}

the later: Use spin locks to deal with wait and notifyAll
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: