public class Test {
// flag为0就打印A,为1就打印B,为2就打印C
// 利用多线程的synchronized关键字,主要使用wait和notify
private int flag = 0;
public synchronized void printA() {
try {
for (int i = 1; i <= 5; i++) {
while (flag != 0) {
this.wait();
}
System.out.println(Thread.currentThread().getName());
flag = 1;
this.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void printB() {
try {
for (int i = 1; i <= 5; i++) {
while (flag != 1) {
this.wait();
}
System.out.println(Thread.currentThread().getName());
flag = 2;
this.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void printC() {
try {
for (int i = 1; i <= 5; i++) {
while (flag != 2) {
this.wait();
}
System.out.println(Thread.currentThread().getName());
flag = 0;
this.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace