Java的wait(), notify()和notifyAll()使用小结

1 篇文章 0 订阅

wait(),notify()和notifyAll()都是java.lang.Object的方法:

wait(): Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object.

notify(): Wakes up a single thread that is waiting on this object's monitor.

notifyAll(): Wakes up all threads that are waiting on this object's monitor.

 

这三个方法,都是Java语言提供的实现线程间阻塞(Blocking)和控制进程内调度(inter-process communication)的底层机制。

1.使用条件 --获得锁

在调用wait(), notify()或notifyAll()的时候,必须先获得锁,且状态变量须由该锁保护

如:synchronized (xxxx)  {
  
     xxxx.wait();

   }

不加锁使用这些方法会出现IllegalMonitorStateException异常.

原因: 在对某个对象上调用wait().notify 等方法进行线程等待或者唤醒(让其他竞争执行该代码的线程上锁)时,没有对该对象执行同步操作。

2.待完----




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值