博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
哲学家就餐问题
阅读量:4230 次
发布时间:2019-05-26

本文共 2057 字,大约阅读时间需要 6 分钟。

假设有五位哲学家围坐在一张圆形餐桌旁,做以下两件事情之一:吃饭,或者思考。吃东西的时候,他们就停止思考,思考的时候也停止吃东西。餐桌中间有一大碗意大利面,每两个哲学家之间有一只餐叉。因为用一只餐叉很难吃到意大利面,所以假设哲学家必须用两只餐叉吃东西。他们只能使用自己左右手边的那两只餐叉。哲学家就餐问题有时也用米饭和筷子而不是意大利面和餐叉来描述,因为很明显,吃米饭必须用两根筷子。哲学家从来不交谈,这就很危险,可能产生死锁,每个哲学家都拿着左手的餐叉,永远都在等右边的餐叉(或者相反)。即使没有死锁,也有可能发生资源耗尽。

/** * 筷子 */public class Chopstick {    private boolean taken=false;    public synchronized void take() throws InterruptedException{        while (taken){            wait();        }        taken=true;    }    public synchronized void drop(){        taken=false;        notifyAll();    }}
/** * 哲学家 */public class Philosopher implements Runnable{    private Chopstick left;    private Chopstick right;    private final int id;    private final int ponderFactor;    private Random rand=new Random(47);    private void pause() throws InterruptedException{        if(ponderFactor==0) return;        TimeUnit.MILLISECONDS.sleep(rand.nextInt(ponderFactor*250));    }    public Philosopher(Chopstick left,Chopstick right,int ident ,int ponder){        this.left=left;        this.right=right;        id=ident;        ponderFactor=ponder;    }    @Override    public void run() {        try {            while(!Thread.interrupted()){                System.out.println(this+" "+" thinking");                pause();                System.out.println(this+" "+"grabbing right");                right.take();                System.out.println(this+" "+" grabbing left");                left.take();                System.out.println(this+" eating");                pause();                right.drop();                left.drop();            }        } catch (InterruptedException e) {            System.out.println(this+" exiting via interrupt");        }    }    public String toString(){        return "Philosopher "+id;    }}
public class DeadlockingDiningPhilosophers {    public static  void main(String[] args)throws  Exception{        int ponder=0;        int size=5;        ExecutorService exec= Executors.newCachedThreadPool();        Chopstick[] sticks=new Chopstick[size];        for(int i=0;i

转载地址:http://zojqi.baihongyu.com/

你可能感兴趣的文章
自动驾驶汽车GPS系统数字孪生建模(一)
查看>>
自动驾驶汽车GPS系统数字孪生建模(二)
查看>>
CUDA 学习(五)、线程块
查看>>
CUDA 学习(八)、线程块调度
查看>>
CUDA 学习(九)、CUDA 内存
查看>>
CUDA 学习(十一)、共享内存
查看>>
游戏感:虚拟感觉的游戏设计师指南——第十四章 生化尖兵
查看>>
游戏感:虚拟感觉的游戏设计师指南——第十五章 超级马里奥64
查看>>
游戏感:虚拟感觉的游戏设计师指南——第十七章 游戏感的原理
查看>>
游戏感:虚拟感觉的游戏设计师指南——第十八章 我想做的游戏
查看>>
游戏设计的艺术:一本透镜的书——第十章 某些元素是游戏机制
查看>>
游戏设计的艺术:一本透镜的书——第十一章 游戏机制必须平衡
查看>>
UVM:7.5.1 期望值与镜像值
查看>>
UVM:7.5.2 常用操作及其对期望值和镜像值的影响
查看>>
UVM:7.6.1 检查后门访问中hdl 路径的sequence
查看>>
UVM:7.6.2 检查默认值的sequence
查看>>
UVM:7.7.1 使用reg_predictor
查看>>
UVM:7.7.2 使用UVM_PREDICT_DIRECT功能与mirror 操作
查看>>
UVM:7.7.3 寄存器模型的随机化与update
查看>>
UVM:7.7.4 扩展位宽
查看>>