用三个线程轮流打印a,b,c,打印十次,java
时间: 2023-06-01 13:03:29 浏览: 101
以下是一种可能的实现:
```java
public class PrintABC {
public static void main(String[] args) {
Printer printer = new Printer();
Thread threadA = new Thread(new PrintTask(printer, 'a'), "Thread A");
Thread threadB = new Thread(new PrintTask(printer, 'b'), "Thread B");
Thread threadC = new Thread(new PrintTask(printer, 'c'), "Thread C");
threadA.start();
threadB.start();
threadC.start();
}
private static class Printer {
private char currentChar = 'a';
private int count = 0;
public synchronized void printChar(char c) {
while (c != currentChar) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(c);
currentChar = (char) ('a' + (currentChar - 'a' + 1) % 3);
count++;
if (count == 30) {
// 打印完十次后结束程序
System.exit(0);
}
notifyAll();
}
}
private static class PrintTask implements Runnable {
private final Printer printer;
private final char c;
public PrintTask(Printer printer, char c) {
this.printer = printer;
this.c = c;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
printer.printChar(c);
}
}
}
}
```
该程序中,`Printer`类维护了当前应该打印的字符`currentChar`和已经打印的次数`count`。`printChar`方法是线程安全的,每个线程在调用该方法时会等待当前应该打印的字符是自己的时候才打印,否则就一直等待。打印完一个字符后,`currentChar`会更新为下一个应该打印的字符,并且会唤醒所有等待的线程(因为下一个应该打印的字符可能是其他线程对应的字符)。
在`main`方法中创建了三个`PrintTask`对象,并将它们分别封装在三个线程中启动。每个`PrintTask`对象负责打印对应的字符,打印十次后就结束。
整个程序的关键在于`Printer`类中的`printChar`方法,它保证了每个线程都能按照规定的顺序打印自己的字符。
阅读全文