哲学家进餐问题是著名的死锁问题,5个哲学家,5根筷子,每个哲学家进餐需要获得左右两根筷子才可以;
信号量
使用信号量完美解决,因为只有5根筷子,所以永远最多只能有两个不相邻的哲学家同时进餐;
选定0号和2号哲学家先开始进餐,每人进餐完毕唤醒下一个人;
// 筷子类
public class Kuaizi {
long id;
public Kuaizi(long id) {
this.id = id;
}
}
// 哲学家类
public class Zhexuejia implements Runnable {
long id;
Kuaizi left, right;
Semaphore semaphore;
Semaphore next;
public Zhexuejia(long id, Kuaizi left, Kuaizi right, Semaphore semaphore, Semaphore next) {
this.id = id;
this.left = left;
this.right = right;
this.semaphore = semaphore;
this.next = next;
}
public void eat() throws InterruptedException {
synchronized (left) {
System.out.println("哲学家" + id + "号拿起左手筷子" + left.id);
TimeUnit.SECONDS.sleep(1);
synchronized (right) {
System.out.println("哲学家" + id + "号拿起右手筷子" + right.id);
TimeUnit.SECONDS.sleep(1);
System.out.println("哲学家" + id + "号吃饭");
TimeUnit.SECONDS.sleep(1);
}
System.out.println("哲学家" + id + "号放下右手筷子" + right.id);
}
System.out.println("哲学家" + id + "号放下左筷子" + left.id);
}
@Override
public void run() {
for (; ; ) {
try {
semaphore.acquire();
eat();
next.release(1);
} catch (InterruptedException e) {
}
}
}
}
// 运行类
public class Test {
public static void main(String[] args) {
Kuaizi k0 = new Kuaizi(0);
Kuaizi k1 = new Kuaizi(1);
Kuaizi k2 = new Kuaizi(2);
Kuaizi k3 = new Kuaizi(3);
Kuaizi k4 = new Kuaizi(4);
Semaphore s0 = new Semaphore(1);
Semaphore s1 = new Semaphore(0);
Semaphore s2 = new Semaphore(1);
Semaphore s3 = new Semaphore(0);
Semaphore s4 = new Semaphore(0);
Zhexuejia z0 = new Zhexuejia(0, k0, k4, s0, s1);
Zhexuejia z1 = new Zhexuejia(1, k1, k0, s1, s2);
Zhexuejia z2 = new Zhexuejia(2, k2, k1, s2, s3);
Zhexuejia z3 = new Zhexuejia(3, k3, k2, s3, s4);
Zhexuejia z4 = new Zhexuejia(4, k4, k3, s4, s0);
ExecutorService executorService = Executors.newFixedThreadPool(5);
executorService.execute(z0);
executorService.execute(z1);
executorService.execute(z2);
executorService.execute(z3);
executorService.execute(z4);
LockSupport.park();
}
}
运行结果
image.png
网友评论