哲学家问题是操作系统中的重要问题,我在这里谈谈对哲学家进餐的理解,同时附上源代码。
哲学家进餐是对多线程的使用,这里有五位哲学家,同时只有五双筷子,如果一个哲学家想要吃饭,必须同时拿起身边的两只筷子。
这样如果没有处理好就会出现死锁,于是我在这里要求第一位哲学家最先使用左边筷子,其他哲学家最先使用右边筷子,这是防止死锁的一种方法。
我把拿筷子和放筷子都作为函数封装起来,在线程调用的时候就直接按照“先拿左边筷子,再拿右边筷子,释放左边,在释放右边的筷子”的步骤进行,知道每个人都吃到饭再结束。
package second;
public class Exe {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
new Thread( new Philosopher(i)).start();
}
}
}
class Philosopher implements Runnable {
static int[] chopsticks = { 1, 1, 1, 1, 1};
int tem;
public Philosopher(int i){
this.tem=i;
}
public void run(){
getChopsticks();
}
public void getChopsticks(){
if (tem==0){//如果是第一个哲学家,先用左边的筷子
if(getLeft(tem)){
if(getRight(tem)){
eating();
freeLeft(tem);
freeRight(tem);
}else{
freeLeft(tem);
}
}else{
System.out.println(tem+"无法获得左手边的筷子");
}
}else{
if(getRight(tem)){
if(getLeft(tem)){
eating();
freeRight(tem);
freeLeft(tem);
}else{
freeRight(tem);
}
}else{
System.out.println(tem+"无法获得右手边的筷子");
}
}
}
public void eating(){
System.out.println(tem + "开始吃饭");
}
public boolean getLeft(int tem){
if(chopsticks[tem]==1){
chopsticks[tem]=0;
System.out.println(tem+"获得左手边的筷子");
return true;
}else{
System.out.println(tem+"不能获得左手边的筷子");
return false;
}
}
public boolean getRight(int tem){
int i= (tem+1)%5;
if(chopsticks[i]==1){
chopsticks[i]=0;
System.out.println(tem+"获得右手边的筷子");
return true;
}else{
System.out.println(tem+"不能获得右手边的筷子");
return false;
}
}
public void freeLeft(int tem){
chopsticks[tem] = 1;
System.out.println(tem+"左手边筷子已释放!");
}
public void freeRight(int tem){
int i = (tem + 1) % 5;
chopsticks[i] = 1;
System.out.println(tem+"右手边筷子已释放!");
}
}