java 哲学家进餐问题
时间: 2023-12-03 20:39:43 浏览: 81
哲学家进餐问题是一个经典的多线程同步问题,Java中可以使用多种方法来解决这个问题,以下是其中两种方法:
方法一:使用ReentrantLock和Condition
```java
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class DiningPhilosophers {
private ReentrantLock[] forks;
private Condition[] conditions;
public DiningPhilosophers(int num) {
forks = new ReentrantLock[num];
conditions = new Condition[num];
for (int i = 0; i < num; i++) {
forks[i] = new ReentrantLock();
conditions[i] = forks[i].newCondition();
}
}
public void startEating(int i) throws InterruptedException {
int leftFork = i;
int rightFork = (i + 1) % forks.length;
if (i % 2 == 0) {
forks[leftFork].lock();
forks[rightFork].lock();
} else {
forks[rightFork].lock();
forks[leftFork].lock();
}
System.out.println("Philosopher " + i + " is eating.");
Thread.sleep(1000);
forks[leftFork].unlock();
forks[rightFork].unlock();
System.out.println("Philosopher " + i + " finished eating.");
}
}
```
方法二:使用Semaphore
```java
import java.util.concurrent.Semaphore;
public class DiningPhilosophers {
private Semaphore[] forks;
private Semaphore maxPhilosophers;
public DiningPhilosophers(int num) {
forks = new Semaphore[num];
for (int i = 0; i < num; i++) {
forks[i] = new Semaphore(1);
}
maxPhilosophers = new Semaphore(num - 1);
}
public void startEating(int i) throws InterruptedException {
int leftFork = i;
int rightFork = (i + 1) % forks.length;
maxPhilosophers.acquire();
forks[leftFork].acquire();
forks[rightFork].acquire();
System.out.println("Philosopher " + i + " is eating.");
Thread.sleep(1000);
forks[leftFork].release();
forks[rightFork].release();
maxPhilosophers.release();
System.out.println("Philosopher " + i + " finished eating.");
}
}
```
阅读全文