注意!! notify 虚拟锁问题,后续补充
package com.qey.learn;
/**
* @ClassName SwapPrint
* @Description
* @Author qianxl
* @Date 2021-03-02 14:46
* @Version 1.1
**/
public class SwapPrint {
public int flag =0;
public synchronized void printA() {
while (flag>=1) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag++;
System.out.println("A");
this.notifyAll();
}
public synchronized void printB() {
while (flag<=0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
flag--;
System.out.println("B");
this.notifyAll();
}
public static void main(String[] args) {
SwapPrint swapPrint = new SwapPrint();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
while(true){
swapPrint.printA();
}
}
});
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
while (true){
swapPrint.printB();
}
}
});
thread1.start();
thread.start();
}
}