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资源,线程进入等待队列
posted @ 2024-03-13 19:38  yangruomao  阅读(3)  评论(0编辑  收藏  举报