有三个线程,分别只能打印A,B和C 要求按顺序打印ABC,打印10次 Java
时间: 2023-10-08 14:05:49 浏览: 43
可以使用线程的 wait() 和 notify() 方法来实现按顺序打印ABC的需求。具体实现如下:
```java
public class PrintABC {
private int times; // 打印次数
private int state; // 当前状态:0-A,1-B,2-C
public PrintABC(int times) {
this.times = times;
this.state = 0;
}
public synchronized void printA() throws InterruptedException {
for (int i = 0; i < times; i++) {
while (state != 0) {
wait();
}
System.out.print("A");
state = 1;
notifyAll();
}
}
public synchronized void printB() throws InterruptedException {
for (int i = 0; i < times; i++) {
while (state != 1) {
wait();
}
System.out.print("B");
state = 2;
notifyAll();
}
}
public synchronized void printC() throws InterruptedException {
for (int i = 0; i < times; i++) {
while (state != 2) {
wait();
}
System.out.print("C");
state = 0;
notifyAll();
}
}
}
```
在主函数中创建三个线程,分别调用 PrintABC 类中的 printA()、printB() 和 printC() 方法:
```java
public static void main(String[] args) {
PrintABC printABC = new PrintABC(10);
Thread threadA = new Thread(() -> {
try {
printABC.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread threadB = new Thread(() -> {
try {
printABC.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread threadC = new Thread(() -> {
try {
printABC.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
threadA.start();
threadB.start();
threadC.start();
}
```
执行结果:
```java
ABCABCABCABCABCABCABCABCABCABC
```