编写Java程序,启动3个线程打印递增的数字,例如,线程1打印1、2、3、4、5,线程2打印6、7、8、9、10,然后线程3打印11、12、13、14、15,接着由线程1打印16、17、18、19、20,依次类推,直到打印到75为止
时间: 2023-10-20 20:11:28 浏览: 135
回答:这是一个技术问题,可以通过使用Java中的多线程编程实现。需要使用循环和判断语句,以及wait()和notify()方法来实现线程协作。具体实现方式可以根据具体情况而定,这里提供一种实现方式供参考:
```
public class PrintThread implements Runnable {
private int startNum;
private final int MAX_NUM = 75;
private static int currentNum = 1;
private int threadId;
private static Object lock = new Object();
public PrintThread(int startNum, int threadId) {
this.startNum = startNum;
this.threadId = threadId;
}
@Override
public void run() {
synchronized (lock) {
int num = startNum;
while (num <= MAX_NUM) {
if (currentNum == num) {
System.out.println("Thread " + threadId + ": " + num);
currentNum++;
lock.notifyAll();
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
num++;
}
lock.notifyAll();
}
}
}
public class Main {
public static void main(String[] args) {
Thread t1 = new Thread(new PrintThread(1, 1));
Thread t2 = new Thread(new PrintThread(6, 2));
Thread t3 = new Thread(new PrintThread(11, 3));
t1.start();
t2.start();
t3.start();
}
}
```
阅读全文