哲学家就餐问题
来源:互联网 发布:淘宝女装美工 编辑:程序博客网 时间:2024/06/16 11:24
import java.util.Random;/* * 问题描述:一圆桌前坐着5位哲学家,两个人中间有一只筷子,桌子中央有面条。 * 哲学家思考问题,当饿了的时候拿起左右两只筷子吃饭,必须拿到两只筷子才能吃饭。 * 上述问题会产生死锁的情况,当5个哲学家都拿起自己右手边的筷子,准备拿左手边的筷子时产生死锁现象。 *//* * 解决办法: 1、添加一个服务生,只有当经过服务生同意之后才能拿筷子,服务生负责避免死锁发生。 2、每个哲学家必须确定自己左右手的筷子都可用的时候,才能同时拿起两只筷子进餐,吃完之后同时放下两只筷子。 3、规定每个哲学家拿筷子时必须拿序号小的那只,这样最后一位未拿到筷子的哲学家只剩下序号大的那只筷子, 不能拿起,剩下的这只筷子就可以被其他哲学家使用,避免了死锁。这种情况不能很好的利用资源。 */class Forks{private int size;private boolean[] isUsed;public Forks(int size) {// TODO Auto-generated constructor stubthis.size = size;isUsed = new boolean[size];}public synchronized void getForks(){int id = Integer.parseInt(Thread.currentThread().getName());//检测是哪个线程while (isUsed[id] || isUsed[(id+1)%size]) {//左右手边有筷子已经被使用了try {wait();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}isUsed[id] = true;isUsed[(id+1)%size] = true;System.out.println(id+":I have getten forks:"+id+","+(id+1)%size);}public synchronized void putDownForks(){int id = Integer.parseInt(Thread.currentThread().getName());//检测是哪个线程isUsed[id] = false;isUsed[(id+1)%size] = false;System.out.println(id+":I have putdown forks:"+id+","+(id+1)%size);notifyAll();}}//每个哲学家线程class Philosopher extends Thread{private String id;//编号private Forks forks;//共用的叉子public Philosopher(String id,Forks forks){this.id = id;this.forks = forks;this.setName(id);}//模拟思考public void think(){System.out.println(id+":I am thinking!");Random random = new Random();try {Thread.sleep(random.nextInt(4)*1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//模拟就餐public void eating(){forks.getForks();//先获取左右两边叉子System.out.println(id+":I am eating!");//开始吃饭Random random = new Random();try {Thread.sleep(random.nextInt(4)*1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}forks.putDownForks();//放下叉子} @Overridepublic void run() {// TODO Auto-generated method stubwhile (true) {think();eating();}}}public class 哲学家进餐问题 {public static void main(String[] args) {final int NUM_OF_PH = 5;Forks forks = new Forks(NUM_OF_PH);for (int i = 0; i < NUM_OF_PH; i++) {new Philosopher(""+i, forks).start();}}}
阅读全文
0 0
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题 锁
- 哲学家就餐问题
- 哲学家就餐问题
- 关于哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 哲学家就餐问题
- 多线程--哲学家就餐问题
- Linux系统日志管理
- HDU 1241 Oil Deposits
- uva 11029 Leading and Trailing
- conda常用命令
- 51nod 1396 还是01串
- 哲学家就餐问题
- matlab绘图时legend显示分式(latex风格)
- ob_flush(); flush(); 1-100显示
- Stream 过滤
- 51nod 1416 两点
- [LeetCode]515. Find Largest Value in Each Tree Row
- nodejs中cookie,session保存内存,缓存,数据库中
- 数据库中查询的数据是多条,可是显示出来的只有一条,为什么?
- 我所理解的Python里method和function的区别(关键词:method/方法/function/函数)