一个简单的例子理解wait和notify两个方法
public class waitnotify {
public static void main(String[] args) {
Object obj = new Object();
Thread t1=new Thread(()-> {
synchronized (obj) {
System.out.println("t1获得了obj的监视器");
try {
System.out.println("t1准备被阻塞了并且释放锁");
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t1获得了obj的监视器,被唤醒了");
}
});
t1.start();
Thread t2=new Thread(()-> {
synchronized (obj) {
System.out.println("这点证明了wait会释放锁,即将准备唤醒被阻塞的t1");
obj.notify();
System.out.println("我唤醒了t1但是我还会把我接下来的代码执行完");
System.out.println("还在t2");
System.out.println("还在t2");
System.out.println("还在t2");
System.out.println("还在t2");
System.out.println("还在t2");
System.out.println("还在t2");
try {
Thread.sleep(5000);
System.out.println("我已经被阻塞5秒了还没轮到t1,所以t1要等我执行完");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t2.start();
}
}
运行结果: