多线程(哲学家吃饭问题)代码实现

哲学家进餐问题描述有五个哲学家,他们的生活方式是交替地进行思考和进餐,哲学家们共用一张圆桌,分别坐在周围的五张椅子上,在圆桌上有五个碗和五支筷子,平时哲学家进行思考,饥饿时便试图取其左、右最靠近他的筷子,只有在他拿到两支筷子时才能进餐,该哲学家进餐完毕后,放下左右两只筷子又继续思考。

约束条件

(1)只有拿到两只筷子时,哲学家才能吃饭。

(2)如果筷子已被别人拿走,则必须等别人吃完之后才能拿到筷子。

代码实现:这个版本的代码直接进行判断2 个筷子的状态

代码如下:

class Taskdemo implements Runnable{
    //初始化筷子的使用状态为false
    private boolean[] chopstick = {false,false,false,false,false};
    @Override
    public void run() {
        //模拟哲学家的活动
        while(true) {
            //思考
            System.out.println("哲学家"+Thread.currentThread().getName()+"思考");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //吃饭
            synchronized (this) {
                //获取两只筷子的状态,
                int num = Integer.parseInt(Thread.currentThread().getName());
                //取余将4号哲学家应该取的是0号的筷子
                if(chopstick[num]||chopstick[(num+1)%5]) {
                    this.notifyAll();
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //当筷子的使用状态为false,使用筷子吃饭
                chopstick[num] = true;
                chopstick[(num+1)%5] = true;
                System.out.println(Thread.currentThread().getName()+"吃饭");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
                //重置筷子的状态属性
                int num1 = Integer.parseInt(Thread.currentThread().getName());
                synchronized (this) {
                    chopstick[num1] = false;
                    chopstick[(num1+1)%5] = false;
                }                    
        }        
    }    
}


public class PhilosopherEating {
    public static void main(String[] args) {
        Taskdemo taskdemo = new Taskdemo();
        Thread thread1 = new Thread(taskdemo, "0");
        Thread thread2 = new Thread(taskdemo, "1");
        Thread thread3 = new Thread(taskdemo, "2");
        Thread thread4 = new Thread(taskdemo, "3");
        Thread thread5 = new Thread(taskdemo, "4");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }

}
 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值