用Java的等待/通知机制实现“厨师一食者”问题。假设分别有6位厨师和6位食者。厨师做一盘菜的时间为3s,食者吃一盘菜的时间为4s。编程实现这一功能
时间: 2024-09-30 22:04:54 浏览: 34
在Java中,我们可以使用`java.util.concurrent`包下的`Semaphore`、`CountDownLatch`或者`CyclicBarrier`来模拟厨师和食者之间的同步问题。这里我们选择`CountDownLatch`和`CyclicBarrier`来解决“厨师一食者”问题,因为它们能够有效地控制任务完成的顺序。
首先,我们需要创建一个`CountDownLatch`用于信号告知所有厨师完成了烹饪,同时还有一个`CyclicBarrier`用于让食者们在收到信号后一起开始用餐:
```java
import java.util.concurrent.*;
public class CookerEaterProblem {
private static final int NUM_COOKS = 6;
private static final int NUM_EATERS = 6;
private static final int COOKING_TIME = 3000; // 3 seconds per dish
private static final int EATING_TIME = 4000; // 4 seconds per dish
public static void main(String[] args) throws InterruptedException {
CountDownLatch cooksDone = new CountDownLatch(NUM_COOKS);
CyclicBarrier barrier = new CyclicBarrier(NUM_EATERS + 1);
// Cookers (threads)
for (int i = 0; i < NUM_COOKS; i++) {
new Thread(() -> cook(cooksDone, barrier)).start();
}
// Eaters (threads)
for (int i = 0; i < NUM_EATERS; i++) {
new Thread(() -> eat(barrier)).start();
}
// Wait for all cooks to finish
cooksDone.await();
System.out.println("All dishes have been cooked and eaten.");
}
private static Runnable cook(CountDownLatch cooksDone, CyclicBarrier barrier) {
return () -> {
try {
Thread.sleep(COOKING_TIME); // Simulate cooking time
System.out.println(Thread.currentThread().getName() + " finished cooking.");
cooksDone.countDown(); // Signal that a dish is ready
barrier.await(); // Wait for all eaters or at least one chef to start eating
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
};
}
private static Runnable eat(CyclicBarrier barrier) {
return () -> {
try {
barrier.await(); // Wait until a dish is ready
System.out.println(Thread.currentThread().getName() + " started eating.");
Thread.sleep(EATING_TIME); // Simulate eating time
System.out.println(Thread.currentThread().getName() + " finished eating.");
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
};
}
}
```
在这个例子中,厨师们会依次烹饪并释放信号,当所有厨师都完成烹饪后,第一个食者会被唤醒并开始吃饭。其他食者会在屏障处等待,直到有足够的一盘菜可供他们食用。
阅读全文