相关博客:
​​并发编程学习之wait()和notify()​​ 在 ​​wati()​​ 方法中有这样一段描述:

public final native void wait(long timeout) throws InterruptedException;
  • This method causes the current thread (call it T) to
  • place itself in the wait set for this object and then to relinquish
  • any and all synchronization claims on this object. Thread T
  • becomes disabled for thread scheduling purposes and lies dormant
  • until one of four things happens:

有一个很关键的地方是 ​​wati()​​​ 方法会释放持有的 ​​synchronized​​​ 的 ​​monitor​​​,那么当被 ​​wait()​​​ 后的线程被 ​​notify()​​​ 后肯定需要再重新获取 ​​synchronized​​​ 的 ​​monitor​​​(因为 ​​wait()​​​ 必须要在 ​​synchronized​​​ 中嘛),那么会从头到尾执行一次 ​​synchronized​​ 中的代码吗?先看这样一段代码:

package com.example.demoClient;

/**
* @author Dongguabai
* @date 2018/12/14 17:47
*/
public class Demo {

private static final Object LOKC = new Object();

private static void doSth(){
System.out.println("开始工作了-------");
synchronized (LOKC){
System.out.println("准备 wait 了---");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("执行结束----");
}
}

public static void main(String[] args) throws InterruptedException {
new Thread(){
@Override
public void run() {
doSth();
}
}.start();

Thread.sleep(1500);

synchronized (LOKC){
LOKC.notify();
}
}
}

输出结果:

wait() 和 notify() 的一个疑问_ide


当 ​​new​​​ 的 ​​Thread​​​ 被唤醒后虽然需要重新获取锁,但是并没有再次输出“准备 wait 了”,即没有再从头到尾执行一次 ​​synchronized​​ 中的代码。