以下是一个简单的Java代码,使用线程和synchronized关键字实现哲学家进餐问题:

public class DiningPhilosophers {

    public static void main(String[] args) {
        Fork[] forks = new Fork[5];
        Philosopher[] philosophers = new Philosopher[5];

        // 初始化叉子
        for (int i = 0; i < 5; i++) {
            forks[i] = new Fork();
        }

        // 初始化哲学家
        for (int i = 0; i < 5; i++) {
            philosophers[i] = new Philosopher(i, forks[i], forks[(i + 1) % 5]);
            new Thread(philosophers[i]).start();
        }
    }

    static class Fork {
        private boolean available = true;

        // 取叉子
        public synchronized void take() throws InterruptedException {
            while (!available) {
                wait();
            }
            available = false;
        }

        // 放叉子
        public synchronized void put() {
            available = true;
            notifyAll();
        }
    }

    static class Philosopher implements Runnable {
        private final int id;
        private final Fork leftFork;
        private final Fork rightFork;

        public Philosopher(int id, Fork leftFork, Fork rightFork) {
            this.id = id;
            this.leftFork = leftFork;
            this.rightFork = rightFork;
        }

        // 进餐
        public void eat() throws InterruptedException {
            leftFork.take();
            rightFork.take();
            System.out.println("Philosopher " + id + " is eating");
            Thread.sleep(1000);
            leftFork.put();
            rightFork.put();
            System.out.println("Philosopher " + id + " is done eating");
        }

        @Override
        public void run() {
            try {
                while (true) {
                    eat();
                    Thread.sleep(1000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

在这个示例中,有五个哲学家和五个叉子。每个哲学家都有一个左边的叉子和一个右边的叉子,他必须拿到两个叉子才能开始进餐。每个叉子都有一个available布尔变量,表示它是否可用。当一个哲学家想要取用叉子时,他会调用take()方法,如果叉子不可用,他会进入等待状态。当他拿到两个叉子开始进餐时,他会调用eat()方法,等待一段时间后放下叉子。在这个过程中,使用synchronized关键字确保在任何时候只有一个哲学家可以取用同一个叉子

请编写一个Java代码解决哲学家进餐问题

原文地址: https://www.cveoy.top/t/topic/frWw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录