1、问题描述(死锁)五个哲学家,五只筷子,只有获得一双筷子之后才能就餐,就有可能出现这种情况:每个哲学家都获得了一只筷子,卡死在那个地方。
2、解决哲学家就餐问题当然后很多方法:(1)有一个服务生来负责避免死锁(2)哲学家在拿筷子的时候,确保左右都有筷子才同时拿起左右两只筷子(3)规定拿筷子的方式:给筷子编号,先拿号码小的筷子 本实现考虑第二种方式:3、java代码实现:class Chopsticks {public static List
static {chops.add(false); //为了方便计算,第一个不会参与计算chops.add(false);chops.add(false);chops.add(false);chops.add(false);} public synchronized void getChop() {String currentName = Thread.currentThread().getName();int index = Integer.parseInt(currentName);while (chops.get(index) || chops.get((index + 1)%5)) {try {wait();} catch (InterruptedException e) {e.printStackTrace();}}chops.set(index, true);chops.set((index + 1)%5 ,true);} public synchronized void freeChop() {String currentName = Thread.currentThread().getName();int index = Integer.parseInt(currentName);chops.set(index, false);chops.set((index + 1)%5 ,false);notifyAll();}} class PhilosopherThread extends Thread {private String name; //线程名称,给哲学家编序号用private Chopsticks chopsticks; public PhilosopherThread (String name, Chopsticks chopsticks) {super(name);// this.name = name;this.chopsticks = chopsticks;} @Overridepublic void run() {while (true) {chopsticks.getChop();System.out.println(Chopsticks.chops);this.eat();chopsticks.freeChop();}} public void eat() {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}} public class PhilosopherTest {public static void main(String[] args) {Chopsticks chopsticks = new Chopsticks();PhilosopherThread philosopherThread1 = new PhilosopherThread("0", chopsticks);PhilosopherThread philosopherThread2 = new PhilosopherThread("1", chopsticks);PhilosopherThread philosopherThread3 = new PhilosopherThread("2", chopsticks);PhilosopherThread philosopherThread4 = new PhilosopherThread("3", chopsticks);PhilosopherThread philosopherThread5 = new PhilosopherThread("4", chopsticks); philosopherThread1.start();philosopherThread2.start();philosopherThread3.start();philosopherThread4.start();philosopherThread5.start();}} 就爱阅读www.92to.com网友整理上传,为您提供最全的知识大全,期待您的分享,转载请注明出处。
来源: http://www.92to.com/bangong/2016/12-07/14010602.html