这篇博客与其他妖艳的骚货不同,它简单易懂(其实是高难度的不会),但是直指问题的本质。(另外和我一样是操作实习的同学不要抄我作业哦)
问题描述:
由Dijkstra提出并解决的哲学家进餐问题(The Dinning Philosophers Problem)是典型的同步问题。该问题是描述有五个哲学家共用一张圆桌,分别坐在周围的五张椅子上,在圆桌上五只筷子,他们的生活方式是交替地进行思考和进餐。平时,一个哲学家进行思考,饥饿时便试图取用其左右最靠近他的筷子,只有在他拿到两只筷子时才能进餐。进餐完毕,放下筷子继续思考。
package 死锁; import java.util.*; public class Sisuo { public static void main(String[] args) { // TODO Auto-generated method stub Integer a = new Integer(0); Integer b = new Integer(0); Integer c = new Integer(0); Integer d = new Integer(0); Integer e = new Integer(0); int arr[]={1,2,3,4,5}; Scanner scan = new Scanner(System.in); System.out.print("请输入最多4位哲学家代号,格式如:输入1 2 3 4 5(不选用的哲学家用0代替,必须凑齐5位数):"); String str = scan.nextLine(); String[] strs = str.split(" "); if(strs.length != 5){ System.out.println("参数输入不合法!"); return; } a = Integer.valueOf(strs[0]); b = Integer.valueOf(strs[1]); c = Integer.valueOf(strs[2]); d = Integer.valueOf(strs[3]); e = Integer.valueOf(strs[4]); int a1=a.intValue(); int b1=b.intValue(); int c1=c.intValue(); int d1=d.intValue(); int e1=e.intValue(); if(a1+b1+c1+d1+e1==15){ System.out.println("出现死锁!"); return; } //要吃饭的都拿起左筷子 if(a1==1){ arr[0]=0; } if(b1==2){ arr[1]=0; } if(c1==3){ arr[2]=0; } if(d1==4){ arr[3]=0; } if(e1==5){ arr[4]=0; } int i=0,num=0; for(int j=0;j<arr.length;j++) {//为最后一个for循环停止 if(arr[j]==0) { i=i+1; } } int m=0,n=0,x=0,z=0,y=0;//这几个变量是核心保证赋值后第一遍循环不会使用 for(int k=0;k<10;k++){ if(a1==1 && m==0){ if(arr[1]==2){ System.out.println("哲学家1号开始进食"); num=num+1; arr[0]=1; a1=0; z =1; } } if(b1==2 && n==0){ if(arr[2]==3){ System.out.println("哲学家2号开始进食"); num=num+1; arr[1]=2; b1=0; m=1; } } if(c1==3 && x==0){ if(arr[3]==4){ System.out.println("哲学家3号开始进食"); num=num+1; arr[2]=3; c1=0; n=1; } } if(d1==4 && y==0){ if(arr[4]==5){ System.out.println("哲学家4号开始进食"); num=num+1; arr[3]=4; d1=0; x=1; } } if(e1==5 && z==0){ if(arr[0]==1){ System.out.println("哲学家5号开始进食"); num=num+1; arr[4]=5; e1=0; y=1; } } m=0;n=0;x=0;z=0;y=0; try { Thread.sleep(3000); } catch (InterruptedException e2) { e2.printStackTrace(); } System.out.println("进食完毕"); if(num==i) { System.out.println("所选哲学家已全部进食完毕,未出现死锁"); break; } } } }