Java 哲学家进餐问题_Java实现哲学家进餐问题 | 学步园

哲学家问题是操作系统中的重要问题,我在这里谈谈对哲学家进餐的理解,同时附上源代码。

哲学家进餐是对多线程的使用,这里有五位哲学家,同时只有五双筷子,如果一个哲学家想要吃饭,必须同时拿起身边的两只筷子。

这样如果没有处理好就会出现死锁,于是我在这里要求第一位哲学家最先使用左边筷子,其他哲学家最先使用右边筷子,这是防止死锁的一种方法。

我把拿筷子和放筷子都作为函数封装起来,在线程调用的时候就直接按照“先拿左边筷子,再拿右边筷子,释放左边,在释放右边的筷子”的步骤进行,知道每个人都吃到饭再结束。

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+"右手边筷子已释放!");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值