0%

哲学家就餐

前言:经典多线程题目-哲学家就餐,java代码

哲学家就餐

问题简述:五位哲学家,五个筷子,当某人又两只筷子时才能进餐。

为了避免死锁,可以采用同时最多4个人就餐

使用java Semaphore(信号量),可以对特定资源的允许同时访问的操作数量进行控制在进行操作的时候,需要先acquire获取到许可,才可以继续执行任务,如果获取失败,则进入阻塞;处理完成之后需要release释放许可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.husky.demo.thread;

import java.util.concurrent.Semaphore;

/**
* @author shency
* @description: TODO
* @date: 2019/11/19
*/
public class Philosopher extends Thread {
private int id;
private Semaphore maxNum;
private Semaphore[] fork;

public Philosopher(int id, Semaphore maxNum, Semaphore[] fork) {
this.id = id;
this.maxNum = maxNum;
this.fork = fork;
}

@Override
public void run() {
try {
maxNum.acquire();
// 拿起左手筷子
fork[id].acquire();
// 拿起右手筷子
fork[(id + 1) % 5].acquire();
System.out.println("第" + (id + 1) + "位哲学家 eating");
// 放下右手筷子
fork[(id + 1) % 5].release();
// 放下左手筷子
fork[id].release();
maxNum.release();
System.out.println("第" + (id + 1) + "位哲学家结束就餐");
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
Semaphore maxNum = new Semaphore(4);
Semaphore[] fork = new Semaphore[5];
for (int i = 0; i < 5; i++) {
fork[i] = new Semaphore(1);
}
Philosopher[] philosophers = new Philosopher[5];
for (int i = 0; i < 5;i++){
philosophers[i] = new Philosopher(i,maxNum,fork);
}
for(Philosopher i:philosophers){
i.start();
}
}
}

运行结果

image-20191230001933491

-------------本文结束感谢您的阅读-------------