哲学家用餐问题——多线程死锁问题

哲学家就餐问题可以这样表述,假设有五位哲学家围坐在一张圆形餐桌旁,餐桌中间有一大碗意大利面,每两个哲学家之间有一只餐叉。因为用一只餐叉很难吃到意大利面,所以假设哲学家必须用两只餐叉吃东西。他们只能使用自己左右手边的那两只餐叉。哲学家就餐问题有时也用米饭和筷子而不是意大利面和餐叉来描述,因为很明显,吃米饭必须用两根筷子,这样可描述为多线程争夺资源的问题。

 由此问题可引入多线程争夺锁的问题,造成相互等待的问题。如果其中至少有一位“左撇子”,可解决此问题:

package Thread;

public class DeadLock {

    public static void main(String[] args) {
        ChopStick cs0 = new ChopStick();
        ChopStick cs1 = new ChopStick();
        ChopStick cs2 = new ChopStick();
        ChopStick cs3 = new ChopStick();
        ChopStick cs4 = new ChopStick();

        Philosohper p0 = new Philosohper("p0", cs0, cs1, 0);
        Philosohper p1 = new Philosohper("p1", cs1, cs2, 1);
        Philosohper p2 = new Philosohper("p2", cs2, cs3, 2);
        Philosohper p3 = new Philosohper("p3", cs3, cs4, 3);
        Philosohper p4 = new Philosohper("p4", cs4, cs0, 4);

        p0.start();
        p1.start();
        p2.start();
        p3.start();
        p4.start();


    }


    public static class Philosohper extends Thread {

        private ChopStick left, right;
        private int index;

        public Philosohper(String name, ChopStick left, ChopStick right, int index) {
            this.setName(name);
            this.left = left;
            this.right = right;
            this.index = index;
        }

        @Override
        public void run() {
            if (index % 2 == 0) {
                synchronized (left) {
                    try {
                        Thread.sleep(1 + index);
                        synchronized (right) {
                            Thread.sleep(index);
                            System.out.println(index + "号已经吃完————————————————————————————————");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            } else {
                synchronized (right) {
                    try {
                        Thread.sleep(1 + index);
                        synchronized (left) {
                            Thread.sleep(index);
                            System.out.println(index + "号已经吃完————————————————————————————————");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }

        }
    }

}

class ChopStick {

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金牌28号技师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值