本文为
sleep是Thread类的方法,wati是Object类的方法
sleep方法可以在任何地方利用
wait只能在synchronized方法或synchronized块中利用
最紧张的实质差异
Thread.sleep只会让出CPU,不会导致锁行为的改变
Object.wait不仅让出CPU,还会开释已经霸占的同步资源锁
示例代码
输出为
Thread A is waiting to get lockThread A get lockThread B is waiting to get lockThread A is doneThread B get lockThread B is done
由输出可以看到Thread.sleep不会开释锁,由于A完成了B才拿到锁
我们将sleep和wait换一下,输出为
Thread A is waiting to get lockThread A get lockThread B is waiting to get lockThread B get lockThread B is doneThread A is done
可以看到Object.wait会开释锁,由于A还没有实行完,锁就被B得到了