1. 程式人生 > >哲學家就餐問題(java實現)

哲學家就餐問題(java實現)

1、問題描述(死鎖) 五個哲學家,五隻筷子,只有獲得一雙筷子之後才能就餐,就有可能出現這種情況:每個哲學家都獲得了一隻筷子,卡死在那個地方。
2、解決哲學家就餐問題當然後很多方法: (1)有一個服務生來負責避免死鎖 (2)哲學家在拿筷子的時候,確保左右都有筷子才同時拿起左右兩隻筷子 (3)規定拿筷子的方式:給筷子編號,先拿號碼小的筷子 本實現考慮第二種方式: 3、java程式碼實現: class Chopsticks { public static List<Boolean> chops = new ArrayList<Boolean>(); 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; } @Override public 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(); } }