java多线程交替打印abc
时间: 2023-03-01 08:21:14 浏览: 152
你可以使用 `synchronized` 和 `wait` / `notify` 来实现多线程交替打印abc。
以下是一个示例代码:
```
public class PrintABC {
private int state;
public synchronized void printA() throws InterruptedException {
while (state % 3 != 0) {
wait();
}
System.out.print("A");
state++;
notifyAll();
}
public synchronized void printB() throws InterruptedException {
while (state % 3 != 1) {
wait();
}
System.out.print("B");
state++;
notifyAll();
}
public synchronized void printC() throws InterruptedException {
while (state % 3 != 2) {
wait();
}
System.out.print("C");
state++;
notifyAll();
}
}
public class Test {
public static void main(String[] args) {
PrintABC printABC = new PrintABC();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
printABC.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
printABC.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
try {
printABC.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
```
上面的代码创建了三个线程,分别调用 `printA`、`printB` 和 `printC` 方法,来实现多线程交替打印abc的功能。
阅读全文