public class CurrentCode {
public synchronized void printA() {
try{
System.out.println("A");
wait(); // 进入wait 等待状态 同时释放锁资源
}catch (InterruptedException e){
e.printStackTrace();
}
}
public synchronized void printB(){
System.out.println("B");
notify(); // 唤醒线程01 ,
try{
wait(); // 释放锁资源
}catch (InterruptedException e){
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
CurrentCode currentCode = new CurrentCode();
new Thread(() -> {
for (int i = 0; i < 5; i++) {
currentCode.printA();
}
}).start();
TimeUnit.MILLISECONDS.sleep(200);
new Thread(() -> {
for (int i = 0; i < 5; i++) {
currentCode.printB();
}
}).start();
}
}
为什么上面的代码只是打印了 :A B A 然后就一直阻塞了,没有执行完毕,主线程也是一直挂起的。
已找到原因,少了一个notify