哲学家用餐问题(Java)

来源:互联网 发布:淘宝加工 编辑:程序博客网 时间:2024/04/28 16:35

哲学家用餐问题大家都很熟悉,是特别经典的死锁问题。这里我想试着用Java来写一下它的模拟和解决。


最简单的解决方式:资源加锁。

即每次只能有一个人吃饭(好不人道啊……)

import java.util.*;class philosoper extends Thread{private static int[] chopstick = new int[5];private int i;public philosoper(int num) {i = num;}public void run() {synchronized (chopstick) {use(this.getName());think(this.getName());}}private void use(String str) {//leftwhile(true) {if(chopstick[i]==0){chopstick[i]++;System.out.println(str + " get left chopstick");break;}}try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO: handle exception}//rightwhile(true) {if(chopstick[(i+1)%5]==0) {chopstick[(i+1)%5]++;System.out.println(str + " get the right chopstick");break;}}//eatSystem.out.println(str + " is eating");}private void think(String str) {chopstick[i]--;chopstick[(i+1)%5]--;System.out.println(str + " is thinking");}}public class Eat {public static void main(String[] args) {for(int i=0; i<5; i++) {Thread t = new philosoper(i);t.start();}}}

缺点:资源极其浪费!!效率极其低下!!!


另一种好一些的方法:超时释放

如果一个人拿到了left,但是等了很久也没拿到right,就让他放弃left,重新开始拿

import java.util.*;class philosoper extends Thread{private static int[] chopstick = new int[5];private int i;public philosoper(int num) {i = num;}public void run() {int flag = 0;getLeft(this.getName());try {              Thread.sleep((long) (Math.random()*1000));          } catch (InterruptedException e) {              e.printStackTrace();          }  flag = getRight(this.getName());while(flag==0) {try {              Thread.sleep((long) (Math.random()*1000));          } catch (InterruptedException e) {              e.printStackTrace();          }  getLeft(this.getName());try {              Thread.sleep((long) (Math.random()*1000));          } catch (InterruptedException e) {              e.printStackTrace();          }  flag = getRight(this.getName());}System.out.println(this.getName() + " is eating");think(this.getName());}private synchronized void getLeft(String str) {//leftwhile(chopstick[i]!=0) {try {                  wait();              } catch (InterruptedException e) {                  e.printStackTrace();              }}chopstick[i]++;System.out.println(str + " get left chopstick");this.notify();}private synchronized int getRight(String str) {int res = 0;while(chopstick[(i+1)%5]!=0) {try {this.wait(3000);if(chopstick[(i+1)%5]!=0){chopstick[i]--;System.out.println(str + " give up left chopstick");return 0;}} catch (InterruptedException e) {e.printStackTrace();}}chopstick[(i+1)%5]++;System.out.println(str + " get right chopstick");notifyAll();return 1;}private void think(String str) {chopstick[i]--;chopstick[(i+1)%5]--;System.out.println(str + " is thinking");}}public class Eat {public static void main(String[] args) {for(int i=0; i<5; i++) {Thread t = new philosoper(i);t.start();}}}



结果图如下:





0 0
原创粉丝点击