JUC源码讲解:wait()

JUC源码讲解:wait()

抛出问题

在线程调用 wait() 时,是否会释放锁?线程的状态是什么样的?会对异常敏感吗?此时CPU资源是否会被释放呢?我们在源码中找找答案吧!

分析源码

进入 wait() 函数,可以看到这样一段代码:

public final void wait() throws InterruptedException {
    wait(0);
}

里面还有一个 wait(0) ,我们点进去看看

public final native void wait(long timeout) throws InterruptedException;

这是一个 native 方法

看到了有异常被抛出,证明是对异常敏感的

至于会不会释放锁,看看注释吧!

有这样一段话:

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.

线程会释放锁资源,直到被 notify 或 notifyAll 唤醒

wait() 方法还会让出CPU时间片,使线程 由RUNNING状态转换为READY状态,进入等待队列中,是释放CPU资源的

总结

  • wait 会释放锁资源,直到被唤醒
  • 源代码中有抛出异常,是对异常敏感的
  • 会让出CPU时间片,释放CPU资源,线程进入等待队列

本文作者:yangruomao

本文链接:https://www.cnblogs.com/yangruomao/p/18071381

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   yangruomao  阅读(15)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起