三个线程,分别输出a,b,c。各输出100次,要求按abc的顺序输出 java
时间: 2024-01-03 22:04:14 浏览: 54
可以使用 Java 的 wait() 和 notify() 方法来实现。
代码如下:
class PrintThread implements Runnable {
private int count;
private Object lock;
private String tag;
public PrintThread(int count, Object lock, String tag) {
this.count = count;
this.lock = lock;
this.tag = tag;
}
public void run() {
for (int i = 0; i < count; i++) {
synchronized (lock) {
while (!tag.equals(Thread.currentThread().getName())) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(tag);
if (tag.equals("c")) {
System.out.println();
}
if (tag.equals("a")) {
tag = "b";
} else if (tag.equals("b")) {
tag = "c";
} else {
tag = "a";
}
lock.notifyAll();
}
}
}
}
public class Main {
public static void main(String[] args) {
Object lock = new Object();
new Thread(new PrintThread(100, lock, "a"), "a").start();
new Thread(new PrintThread(100, lock, "b"), "b").start();
new Thread(new PrintThread(100, lock, "c"), "c").start();
}
}
阅读全文