哲学家就餐问题是1965年由Dijkstra提出的一种线程同步的问题。
问题描述:一圆桌前坐着5位哲学家,两个人中间有一只筷子,桌子中央有面条。哲学家思考问题,当饿了的时候拿起左右两只筷子吃饭,必须拿到两只筷子才能吃饭。上述问题会产生死锁的情况,当5个哲学家都拿起自己右手边的筷子,准备拿左手边的筷子时产生死锁现象。
解决办法:
1、添加一个服务生,只有当经过服务生同意之后才能拿筷子,服务生负责避免死锁发生。
2、每个哲学家必须确定自己左右手的筷子都可用的时候,才能同时拿起两只筷子进餐,吃完之后同时放下两只筷子。
3、规定每个哲学家拿筷子时必须拿序号小的那只,这样最后一位未拿到筷子的哲学家只剩下序号大的那只筷子,不能拿起,剩下的这只筷子就可以被其他哲学家使用,避免了死锁。这种情况不能很好的利用资源。
参考:http://www.cnblogs.com/vettel/p/3438257.html
package 操作系统; class Philosopher extends Thread { private String name; private Fork fork; public Philosopher(String name, Fork fork) { super(); this.name = name; this.fork = fork; } @Override public void run() { thinking(); fork.takeFork(); eating(); fork.putFork(); } void eating() { System.out.println("I'm eating " + name); try { sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void thinking() { System.out.println("I'm thinking" + name); try { sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } class Fork { boolean[] used = { false, false, false, false, false }; synchronized void takeFork() { String threadName = Thread.currentThread().getName(); String name = threadName.substring(threadName.length()-1, threadName.length()); int i = Integer.parseInt(name); while (used[i] || used[(i + 1) % 5]) { try { wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } used[i] = true; used[(i + 1) % 5] = true; } synchronized void putFork() { String threadName = Thread.currentThread().getName(); String name = threadName.substring(threadName.length()-1, threadName.length()); int i = Integer.parseInt(name); used[i] = false; used[(i + 1) % 5] = false; notifyAll(); } } public class 哲学家就餐问题 { public static void main(String[] args) { Fork fork = new Fork(); new Philosopher("1", fork).start(); new Philosopher("2", fork).start();; new Philosopher("3", fork).start();; new Philosopher("4", fork).start();; new Philosopher("5", fork).start();; } }
执行结果
I'm thinking1
I'm thinking3
I'm thinking2
I'm thinking4
I'm thinking5
I'm eating 1
I'm eating 3
I'm eating 5
I'm eating 2
I'm eating 4
