三个线程,分别输出a,b,c。各输出100次,要求按abc的顺序输出 java
时间: 2024-01-03 16:03:29 浏览: 113
这个问题可以直接回答。可以使用synchronized关键字来同步三个线程,确保按照abc的顺序输出。代码如下:
```
class PrintThread implements Runnable {
private static Object lock = new Object(); // 静态锁
private String toPrint; // 要输出的字母
private int times; // 输出次数
public PrintThread(String toPrint, int times) {
this.toPrint = toPrint;
this.times = times;
}
public void run() {
for (int i = 0; i < times; i++) {
synchronized (lock) {
while (!toPrint.equals(curLetter)) { // 不是当前字母,等待
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(toPrint); // 输出当前字母
if (toPrint.equals("c")) System.out.println(); // 输出完c后换行
switch (toPrint) { // 更改当前字母
case "a":
curLetter = "b";
break;
case "b":
curLetter = "c";
break;
case "c":
curLetter = "a";
break;
}
lock.notifyAll(); // 唤醒等待线程
}
}
}
}
public class Test {
private static String curLetter = "a"; // 当前要输出的字母
public static void main(String[] args) {
new Thread(new PrintThread("a", 100)).start();
new Thread(new PrintThread("b", 100)).start();
new Thread(new PrintThread("c", 100)).start();
}
}
```
笑话:为什么码农喜欢喝奶茶呢?因为奶茶里有异步。
阅读全文