题目:按顺序打印 ABC ABC ABC ...。有这么一个多线程场景问题:有三个线程,线程1执行(输出A)完成之后线程2执行(输出B),线程2执行完之后线程3执行(输出C),线程3执行完成之后线程1执行...,整体循环50次,写程序实现。
代码:
class PrintABC {
private volatile int value = 1;
void printA() {
synchronized (this) {
while (value != 1) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread1: A");
value = 2;
//唤醒
notifyAll();
}
}
void printB() {
synchronized (this) {
while (value != 2) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread2: B");
value = 3;
notifyAll();
}
}
void printC() {
synchronized (this) {
while (value != 3) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Thread3: C");
value = 1;
notifyAll();
}
}
}
public class 多线程的应用{
public static void main(String[] args) throws Exception {
PrintABC printABC = new PrintABC();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 50; i++) {
printABC.printA();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 50; i++) {
printABC.printB();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 50; i++) {
printABC.printC();
}
}
}).start();
}
}
测试结果:



