Java之也谈sleep()和wait()
来源:互联网 发布:中国有嘻哈冠军知乎 编辑:程序博客网 时间:2024/05/21 14:10
讨论sleep()和wait()的很多文章流传蛮广,甚至有些都是错误的。那我我也谈谈自己的观点。
首先sleep(),直接看官方文档
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
加红的文字表明比如在synchronized (obj){...}语句块中执行Thread.sleep()不会丢失obj锁。
接着wait(),
notify()
method or the notifyAll()
method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0)
.The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify
method or the notifyAll
method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
As in the one argument version, interrupts and spurious wakeups are possible, and this method should always be used in a loop:
synchronized (obj) { while (<condition does not hold>) obj.wait(); ... // Perform action appropriate to condition }This method should only be called by a thread that is the owner of this object's monitor. See the
notify
method for a description of the ways in which a thread can become the owner of a monitor.tips:
我说网上文章是错误的是关于时间片的说法,说wait()不占用时间片,sleep()占用时间片。如果是真的,不仅官方文档中对这么重要的事情,提都不提实属不该,而且我实测中,无论是wait()或者sleep()都是释放了cpu的控制权的。
- Java之也谈sleep()和wait()
- java wait()和sleep()方法之经验谈
- java wait()和sleep()方法之经验谈
- java之sleep和wait的区别
- java wait()和sleep()方法之经验谈
- Java之wait()/sleep()和notify()/notifyAll()
- Java中的sleep()和wait()
- Java线程wait和sleep
- Java多线程之sleep,wait,join和yield关键字
- java之yield(),sleep(),wait()区别详解
- java知识系列之yield(),sleep(),wait()
- java之yield,sleep,wait详解
- java之yield(),sleep(),wait()区别详解
- java之yield(),sleep(),wait()详解
- java之yield(),sleep(),wait()区别
- java之yield(),sleep(),wait()区别
- java之yield(),sleep(),wait()区别详解
- java之yield(),sleep(),wait()等区别
- 一颗初心,慢煮岁月(最美文字)
- C++中int型128转入char型变量c中
- shell小节--源自网站“神算子”:www.wangsenfeng.com
- 10.1训练赛--2014上海区域赛--- World Cup**
- swap--源自网站“神算子”:www.wangsenfeng.com
- Java之也谈sleep()和wait()
- vi 显示行号-----源自网站“神算子”:www.wangsenfeng.com
- window7使用eclipse环境本地运行MapReduce程序方法-----源自网站“神算子”:www.wangsenfeng.com
- iOS编程-------UIScrollView / UIPageControl
- window7使用eclipse提交Hadoop作业到Hadoop集群运行方法
- wordcount学习
- MySql实现主从热备和读写分离
- zookeeper的watcher示意图
- Linux的常用数据结构之链表