启动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. JAVA实现
时间: 2023-09-30 18:07:51 浏览: 72
可以使用 Java 的多线程和锁机制来实现这个需求。以下是一个可能的实现:
```
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class IncrementalNumberPrinter {
private static final int MAX_NUMBER = 75;
private static final int NUM_THREADS = 3;
private static final int NUM_NUMBERS_PER_THREAD = MAX_NUMBER / NUM_THREADS;
private int currentNumber = 1;
private int currentThreadId = 1;
private final Lock lock = new ReentrantLock();
private final Condition[] conditions = new Condition[NUM_THREADS];
public IncrementalNumberPrinter() {
for (int i = 0; i < NUM_THREADS; i++) {
conditions[i] = lock.newCondition();
}
}
public void start() throws InterruptedException {
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
int threadId = i + 1;
threads[i] = new Thread(() -> {
try {
printNumbers(threadId);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
return;
}
});
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
}
private void printNumbers(int threadId) throws InterruptedException {
while (currentNumber <= MAX_NUMBER) {
lock.lock();
try {
while (threadId != currentThreadId) {
conditions[threadId - 1].await();
}
int startNumber = (threadId - 1) * NUM_NUMBERS_PER_THREAD + 1;
int endNumber = threadId * NUM_NUMBERS_PER_THREAD;
for (int i = startNumber; i <= endNumber; i++) {
System.out.println(i);
currentNumber++;
}
currentThreadId = (currentThreadId % NUM_THREADS) + 1;
conditions[currentThreadId - 1].signalAll();
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
IncrementalNumberPrinter printer = new IncrementalNumberPrinter();
printer.start();
}
}
```
这个实现中,我们用一个 `currentNumber` 变量来记录当前要打印的数字,用一个 `currentThreadId` 变量来记录当前正在执行打印操作的线程编号。每个线程在执行打印操作前,都会先检查 `currentThreadId` 变量,如果不是自己的编号,则等待;如果是自己的编号,则按照要求打印一段数字,然后更新 `currentThreadId` 变量,并唤醒下一个线程。
注意,由于 `lock` 和 `condition` 是对象,而不是类,所以我们要在构造函数中初始化它们。另外,我们在 `printNumbers` 方法中使用了 `try-finally` 块来确保在出现异常时也能正确释放锁。最后,在 `main` 方法中创建 `IncrementalNumberPrinter` 对象并调用 `start` 方法即可启动程序。
阅读全文