wait(),notify(),notifyAll()必须加锁的原因
2024-10-20 03:37:22
从语义方面解析为什么需要锁:
1、wait()方法会释放锁,如果没有先获得锁,那么如何释放?
从实际的作用:
为了预防饥饿线程的产生。
原因:
// 线程A 的代码
while(!condition){ // 不能使用 if , 因为存在一些特殊情况, 使得线程没有收到 notify 时也能退出等待状态
wait();
}
// do something
// 线程 B 的代码
if(!condition){
// do something ...
condition = true;
notify();
}
现在考虑, 如果wait() 和 notify() 的操作没有相应的同步机制, 则会发生如下情况
【线程A】 进入了 while 循环后(通过了 !condition 判断条件, 但尚未执行 wait 方法), CPU 时间片耗尽, CPU 开始执行线程B的代码
【线程B】 执行完毕了 condition = true; notify(); 的操作, 此时【线程A】的 wait() 操作尚未被执行, notify() 操作没有产生任何效果
【线程A】执行wait() 操作, 进入等待状态,如果没有额外的 notify() 操作, 该线程将持续在 condition = true 的情形下, 持续处于等待状态得不到执行。
原文链接:https://blog.csdn.net/lengxiao1993/article/details/52296220
最新文章
- 基于AutoCAD的ObjectARX之NET扩展(mcnetarx)-AcdbEntGet
- POJ - 2253 Frogger(Dijkstra变形题)
- 一个简单的任务执行时间监视器 StopWatch
- paip.简化字-手写参考二简字..共98个
- Lua环境
- Daily Scrum – 1/19
- Android 云服务器的搭建和友盟APP自动更新功能的实现
- HTML标签使用特写
- [矩阵快速幂]HDOJ4565 So Easy!
- Cookie中文乱码问题
- 开涛spring3(6.1) - AOP 之 6.1 AOP基础
- dedecms 在php5.4以上环境下 无法保存中文
- [LeetCode] Set Intersection Size At Least Two 设置交集大小至少为2
- hdu5631 BestCoder Round #73 (div.2)
- 用js来实现那些数据结构11(字典)
- Spring MVC 数据绑定 (四)
- 开发中常用js记录(三)
- 解决mapper绑定异常:nested exception is org.apache.ibatis.binding.BindingException:
- su、sudo、su - root的区别
- dos命令收集