java基础(五):Java同步机制之notify vs notifyAll

本文深入探讨了Java中wait和notify机制的基本原理与使用方法。强调了这些方法必须在同步块中调用,并详细解释了notify与notifyAll的区别及应用场景。此外,文章还提供了正确的wait方法调用方式以及如何确保线程等待条件得到满足的有效策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 ExpandedBlockStart.gif ContractedBlock.gif synchronized (obj)  {
2ExpandedSubBlockStart.gifContractedSubBlock.gif    while(<condition does not hold>{
3InBlock.gif       wait(); 
4InBlock.gif        // Perform action appropriate to condition
5ExpandedSubBlockEnd.gif       }

6ExpandedBlockEnd.gif }

the later: Use spin locks to deal with wait and notifyAll
95799.html

crazycy 2007-01-24 20:14 发表评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值