从语义方面解析为什么需要锁:

  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

最新文章

  1. 基于AutoCAD的ObjectARX之NET扩展(mcnetarx)-AcdbEntGet
  2. POJ - 2253 Frogger(Dijkstra变形题)
  3. 一个简单的任务执行时间监视器 StopWatch
  4. paip.简化字-手写参考二简字..共98个
  5. Lua环境
  6. Daily Scrum – 1/19
  7. Android 云服务器的搭建和友盟APP自动更新功能的实现
  8. HTML标签使用特写
  9. [矩阵快速幂]HDOJ4565 So Easy!
  10. Cookie中文乱码问题
  11. 开涛spring3(6.1) - AOP 之 6.1 AOP基础
  12. dedecms 在php5.4以上环境下 无法保存中文
  13. [LeetCode] Set Intersection Size At Least Two 设置交集大小至少为2
  14. hdu5631 BestCoder Round #73 (div.2)
  15. 用js来实现那些数据结构11(字典)
  16. Spring MVC 数据绑定 (四)
  17. 开发中常用js记录(三)
  18. 解决mapper绑定异常:nested exception is org.apache.ibatis.binding.BindingException:
  19. su、sudo、su - root的区别
  20. dos命令收集

热门文章

  1. vue echarts 给双饼图添加点击事件
  2. 洛谷 P2212 [USACO14MAR]浇地Watering the Fields 题解
  3. 洛谷P3177 树上染色
  4. Java基础教程(全代码解析)
  5. ajax post data 获取不到数据,注意 content-type的设置 、post/get(转)
  6. coci2011 debt 还债
  7. 用docker构建redis cluster
  8. Spring Cloud Eureka源码分析 --- client 注册流程
  9. 爬虫中Requests模块
  10. Redis 密码设置 及 带密码访问