问题
Java使用三个线程循环顺序打印A、B、C。
思路一
使用synchronized、wait()、notifyAll()、value值决定线程的执行顺序。
代码
class PrintABC {
private volatile int value = 1;
void printA() {
synchronized (this) {
while (value != 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": A");
value = 2;
notifyAll();
}
}
void printB() {
synchronized (this) {
while (value != 2) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": B");
value = 3;
notifyAll();
}
}
void printC() {
synchronized (this) {
while (value != 3) {
try {