哲学家就餐问题 锁

哲学家类:

package cn.com.alfred; public class Philosopher extends Thread{ private Dinner dinner; private boolean isEating; private int num; public Philosopher(Dinner dinner, int num) { this.dinner = dinner; this.num = num; isEating = false; } @Override public void run() { while(true) { getChopsticks(); eat(); think(); } } private void think() { // TODO Auto-generated method stub try { sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void eat() { // TODO Auto-generated method stub try { sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } setStatus(false); dinner.setchopsticksByIndex(num, false); dinner.setchopsticksByIndex((num + 1) % dinner.getCount(), false); } private synchronized void getChopsticks() { // TODO Auto-generated method stub while(!chopsticksFree()) { try { wait(); }catch (InterruptedException e) { e.printStackTrace(); } } dinner.setchopsticksByIndex(num, true); dinner.setchopsticksByIndex((num + 1) % dinner.getCount(), true); setStatus(true); dinner.statusPrint(); notifyAll(); } private boolean chopsticksFree() { // TODO Auto-generated method stub if(dinner.getchopsticksByIndex(num)) return false; if(dinner.getchopsticksByIndex((num + 1) % dinner.getCount())) return false; return true; } public void setStatus(boolean status) { // TODO Auto-generated method stub isEating = status; } public boolean getStatus() { // TODO Auto-generated method stub return isEating; } }  

 

测试类:

package cn.com.alfred; import java.util.Arrays; public class Dinner { private int n = 10; private Philosopher[] p; private boolean[] chopsticks; private int count; public static void main(String[] args) { Dinner self = new Dinner(); self.init(); } private void init() { p = new Philosopher[n]; chopsticks = new boolean[n]; Arrays.fill(chopsticks, false); for(int i = 0; i < n; i++) { p[i] = new Philosopher(this, i); p[i].setPriority(Thread.NORM_PRIORITY - 1); p[i].start(); } } public boolean getchopsticksByIndex(int index) { return chopsticks[index]; } public void setchopsticksByIndex(int index, boolean status) { chopsticks[index] = status; } public int getCount() { return n; } public synchronized void statusPrint() { System.out.println("第" + count + "次"); for(int i = 0; i < n; i++) { String s = "Philosopher " + i + " is "; if(p[i].getStatus()) s += "eating"; else s += "thinking"; System.out.println(s); } System.out.println(); count++; } }  

你可能感兴趣的:(哲学家就餐问题 锁)