用java写一个三个线程轮询打印到控制台1-100
时间: 2023-04-01 17:03:18 浏览: 154
我可以回答这个问题。以下是一个用 Java 编写的三个线程轮询打印到控制台 1-100 的示例代码:
```
public class PrintNumber implements Runnable {
private static int number = 1;
private int threadId;
private static Object lock = new Object();
public PrintNumber(int threadId) {
this.threadId = threadId;
}
@Override
public void run() {
while (number <= 100) {
synchronized (lock) {
if (number % 3 == threadId) {
System.out.println("Thread " + threadId + ": " + number);
number++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new PrintNumber());
Thread t2 = new Thread(new PrintNumber(1));
Thread t3 = new Thread(new PrintNumber(2));
t1.start();
t2.start();
t3.start();
}
}
```
这个程序创建了三个线程,每个线程轮流打印 1-100 中对应线程编号余数为 、1、2 的数字。使用 synchronized 和 wait/notifyAll 实现线程间的同步。