java之哲学家问题(二)

多个哲学家的中间都有一根筷子,哲学家左右需要一根筷子才能吃饭,怎么才能吃上饭

package com.company;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) throws Exception {
	// write your code here
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String number = bufferedReader.readLine();
        Integer count = Integer.valueOf(number);

        List<Chopsticks> chopsticksList = new ArrayList<>(count);
        for (int i = 1; i <= count; i++) {
            chopsticksList.add(new Chopsticks(i));
        }

        List<Philosopher> philosopherList = new ArrayList<>(count);
        Philosopher philosopher;
        for (int i = 0; i < count; i++) {
            if (i % 2 == 0) {
                philosopher = new Philosopher(i + 1, chopsticksList.get(i), chopsticksList.get(i + 1 >= count ? 0 : i + 1));
            } else {
                philosopher = new Philosopher(i + 1, chopsticksList.get(i + 1 >= count ? 0 : i + 1), chopsticksList.get(i));
            }

            philosopherList.add(philosopher) ;
        }

        for (int i = 0; i < count; i++) {
            int index = i;
            new Thread(() -> philosopherList.get(index).eat()).start();
        }
    }


    static class Chopsticks {
        private int index;
        public Chopsticks(int index) {
            this.index = index;
        }
    }

    static class Philosopher {
        private int index;
        private Chopsticks left;
        private Chopsticks right;
        public Philosopher(int index, Chopsticks left, Chopsticks right) {
            this.index = index;
            this.left = left;
            this.right = right;
        }

        public void eat() {
            try {
                synchronized(left) {
                    System.out.println("第" + index + "个哲学家拿到了第一个筷子");
                    Thread.sleep(1000);
                    synchronized (right) {
                        System.out.println("第" + index + "个哲学家拿到了第二个的筷子");
                        Thread.sleep(3000);
                        System.out.println("第" + index + "个哲学家吃完了");
                    }
                }
            } catch (Exception e) {

            }
        }
    }
}

结果如下:

5
第1个哲学家拿到了第一个筷子
第3个哲学家拿到了第一个筷子
第5个哲学家拿到了第一个筷子
第1个哲学家拿到了第二个的筷子
第3个哲学家拿到了第二个的筷子
第3个哲学家吃完了
第1个哲学家吃完了
第2个哲学家拿到了第一个筷子
第5个哲学家拿到了第二个的筷子
第2个哲学家拿到了第二个的筷子
第5个哲学家吃完了
第4个哲学家拿到了第一个筷子
第4个哲学家拿到了第二个的筷子
第2个哲学家吃完了
第4个哲学家吃完了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值