从源码注释中了解 sleep 和 wait 的区别(JDK 8)

22 篇文章 2 订阅

sleep 指的是 java.lang.Thread#sleep(long)
wait 指的是 java.lang.Object#wait()

一、源码注释

sleep :

在这里插入图片描述

wait :

在这里插入图片描述

这里调用了 wait(0);,所以这里也贴出 wait(long)。

wait(long) :

在这里插入图片描述
在这里插入图片描述

二、解读

2.1、sleep

从注释中可以得到如下几点:

1、thread to sleep
线程进入休眠,线程的状态是TIMED_WAITING

2、The thread does not lose ownership of any monitors.
线程虽然进入了休眠,但是不会失去所拥有的锁。

3、IllegalArgumentException – if the value of millis is negative
入参不能为负数。

4、 InterruptedException – if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.
假如该线程已经进入休眠,这时候中断该线程,那么该线程的中断状态将会被复位,同时抛出异常InterruptedException

2.2、wait

从注释中可以得到如下几点:

1、thread to wait
线程进入等待,线程的状态是WAITING

2、until another thread invokes the notify() method or the notifyAll() method for this object.
线程的唤醒,需要其他线程调用对象的 notify() 方法或者 notifyAll() 方法。

3、The current thread must own this object's monitor.
在使用wait 方法时,当前线程必须要先获取该对象的 monitor,即对象锁。

4、The thread releases ownership of this monitor
该方法会释放当前线程锁。

5、The thread then waits until it can re-obtain ownership of the monitor and resumes execution.
线程在唤醒的时候,需要重新竞争对象锁。

6、
在这里插入图片描述

就像只有一个参数的版本方法一样,可能会出现伪唤醒(spurious wakeups),所以要使用这种循环模式。

好的,那么我们来看一下只有一个参数的版本是怎么说的?也就是 wait(long)的说明:

在这里插入图片描述
线程可能被唤醒,不是用的 notify,而是中断,或者时间到了,这种被称为 “ 伪唤醒 ”。 虽然在实践中出现的几率很小,但是在 wait 被唤醒,我们最后还是重新判断一下条件,如果条件不成立,就继续等待。

有意思的地方,这个推荐了两本书,如果想了解的更多的话。好的,我刚好有这两本书,记录如下:
《Concurrent Programming in Java》(《Java并发编程实战》)
《Effective Java Programming Language Guide》
https://blog.csdn.net/u013490280/article/details/108762821

7、IllegalMonitorStateException – if the current thread is not the owner of the object's monitor.
没有获得对象锁时会抛出的异常IllegalMonitorStateException

8、InterruptedException – if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.
线程wait以后,被中断操作时,会将中断状态复位,并抛出异常InterruptedException

其他

https://blog.csdn.net/qq_20009015/article/details/89980966

https://blog.csdn.net/weixin_41101173/article/details/79889464

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值