哲学家就餐问题(java全代码)

2023-11-23 12:44

本文主要是介绍哲学家就餐问题(java全代码),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

题目

有N个哲学家围坐在一张圆桌旁,桌上只有N把叉子,每对哲学家中间各有一把。

哲学家的两种行为:

一、思考

二、吃意大利面

哲学家只能拿起手边左边或右边的叉子

吃饭需要两把叉子

正确地模仿哲学家的行为

方法一

一次只允许四个人抢叉子
import java.util.concurrent.Semaphore;
class 方法一 {public static class PhilosopherTest {//一次只允许四个人抢叉子static final Semaphore count = new Semaphore(4);//五只叉子static final Semaphore[] mutex = {new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1)};static class Philosopher extends Thread {Philosopher(int name) {super.setName(String.valueOf(name));}@Overridepublic void run() {do {try {//只有四个人有抢叉子的资格count.acquire();Integer i = Integer.parseInt(super.getName());//规定都先拿左手边的叉子,于是四个人左手都有叉子mutex[i].acquire();//大家开始抢右边的叉子mutex[(i + 1) % 5].acquire();//谁先抢到谁第一个开吃System.out.println("哲学家" + i + "号吃饭!");//吃完放下左手的叉子,对于左边人来说,就是他的右叉子,直接开吃mutex[i].release();//再放下右手的叉子mutex[(i + 1) % 5].release();//吃完了,开始思考,由于放下了右手的叉子,相当于给一个叉子没有的哲学家一个左叉子count.release();//模拟延迟Thread.sleep(2000);} catch (InterruptedException e) {System.out.println("异常");}} while (true);}}public static void main(String[] args) {Philosopher[] threads=new Philosopher[5];for (int i = 0; i < 5; i++) {threads[i] = new Philosopher(i);}for (Philosopher i : threads) {i.start();}}}
}

count每次acquire就会减一,使得第五个来访问的哲学家被阻塞

下面是将think和eat方法分离出来的改进版本:

import java.util.concurrent.Semaphore;
public class 方法一改进 {public static class PhilosopherTest {// 一次只允许四个人抢叉子static final Semaphore count = new Semaphore(4);// 五只叉子static final Semaphore[] mutex = {new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1)};static class Philosopher extends Thread {Philosopher(int name) {super.setName(String.valueOf(name));}@Overridepublic void run() {do {try {think();eat();} catch (InterruptedException e) {System.out.println("异常");}} while (true);}public void think() throws InterruptedException {// 模拟思考System.out.println("哲学家" + super.getName() + "号正在思考");Thread.sleep(2000); // 模拟延迟}public void eat() throws InterruptedException {// 只有四个人有抢叉子的资格count.acquire();Integer i = Integer.parseInt(super.getName());// 规定都先拿左手边的叉子,于是四个人左手都有叉子mutex[i].acquire();// 大家开始抢右边的叉子mutex[(i + 1) % 5].acquire();// 谁先抢到谁第一个开吃System.out.println("哲学家" + i + "号吃饭!");// 吃完放下左手的叉子,对于左边人来说,就是他的右叉子,直接开吃mutex[i].release();// 再放下右手的叉子mutex[(i + 1) % 5].release();// 吃完了,开始思考,由于放下了右手的叉子,相当于给一个叉子没有的哲学家一个左叉子count.release();}}public static void main(String[] args) {PhilosopherTest.Philosopher[] threads=new PhilosopherTest.Philosopher[5];for (int i = 0; i < 5; i++) {threads[i] = new PhilosopherTest.Philosopher(i);}for (PhilosopherTest.Philosopher i : threads) {i.start();}}}}

本质没区别。

方法二

先获取左筷子,一段时间内申请不到右筷子就将左筷子释放
import java.util.concurrent.Semaphore;public class 方法二 {//先获取左筷子,一段时间内申请不到右筷子就将左筷子释放// Five forksstatic final Semaphore[] mutex = {new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1)};static class Philosopher extends Thread {Philosopher(int name) {super.setName(String.valueOf(name));}@Overridepublic void run() {do {try {Integer i = Integer.parseInt(super.getName());//尝试获取左筷子if (mutex[i].tryAcquire()) {//尝试获取右筷子if (mutex[(i + 1) % 5].tryAcquire()) {System.out.println("哲学家" + i + "号吃饭!");mutex[i].release();mutex[(i + 1) % 5].release();Thread.sleep(2000);} else {//如果获取不到右筷子,就把左筷子扔了mutex[i].release();}}//这里没有else,获取不到左筷子就一直尝试} catch (InterruptedException e) {System.out.println("异常");}} while (true);}}public static void main(String[] args) {Philosopher[] threads=new Philosopher[5];for (int i = 0; i < 5; i++) {threads[i] = new Philosopher(i);}for (Philosopher i : threads) {i.start();}}
}

下面是将eat和think分出来的版本:

import java.util.concurrent.Semaphore;
class 方法二改进 {//先获取左筷子,一段时间内申请不到右筷子就将左筷子释放public static class Philosopher extends Thread {private static Semaphore[] chopsticks = {new Semaphore(1), new Semaphore(1), new Semaphore(1), new Semaphore(1), new Semaphore(1)};private int id;public Philosopher(int id) {this.id = id;}@Overridepublic void run() {while (true) {think();eat();}}public void think() {System.out.println("哲学家_" + this.id + "正在思考");//思考一秒时间try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}public void eat() {try {if (chopsticks[this.id].tryAcquire()) { // 获取左筷子if (chopsticks[(this.id + 1) % chopsticks.length].tryAcquire()) { // 获取右筷子System.out.println("哲学家_" + this.id + "正在吃饭");// 吃饭花一秒时间try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();} finally {chopsticks[this.id].release(); // 放下左筷子chopsticks[(this.id + 1) % chopsticks.length].release(); // 放下右筷子}} else {chopsticks[this.id].release(); // 如果不能获取右筷子,释放左筷子}}} catch (Exception e) {e.printStackTrace();}}public static void main(String[] args) {Philosopher[] threads=new Philosopher[5];for (int i = 0; i < 5; i++) {threads[i] = new Philosopher(i);}for (Philosopher i : threads) {i.start();}}}}

下面是用可重入锁实现的版本:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;class Philosopher extends Thread {private Lock leftFork;private Lock rightFork;private int philosopherId;private int eatCount; // 计数器public Philosopher(int philosopherId, Lock leftFork, Lock rightFork) {this.philosopherId = philosopherId;this.leftFork = leftFork;this.rightFork = rightFork;this.eatCount = 0;}private void think() throws InterruptedException {System.out.println("Philosopher " + philosopherId + " is thinking.");Thread.sleep((long) (Math.random() * 1000));}private void eat() throws InterruptedException {System.out.println("Philosopher " + philosopherId + " is eating.");Thread.sleep((long) (Math.random() * 1000));eatCount++;}@Overridepublic void run() {try {while (eatCount < 1) { // 表示每个哲学家吃了1次think();/* 使用ReentrantLock锁, 该类中有一个tryLock()方法, 在指定时间内获取不到锁对象, 就从阻塞队列移除,不用一直等待。当获取了左手边的筷子之后, 尝试获取右手边的筷子, 如果该筷子被其他哲学家占用, 获取失败, 此时就先把自己左手边的筷子,给释放掉. 这样就避免了死锁问题 */if (leftFork.tryLock()) {System.out.println("Philosopher " + philosopherId + " picked up left fork.");if (rightFork.tryLock()) {System.out.println("Philosopher " + philosopherId + " picked up right fork.");eat();rightFork.unlock();System.out.println("Philosopher " + philosopherId + " put down right fork.");}leftFork.unlock();System.out.println("Philosopher " + philosopherId + " put down left fork.");}}} catch (InterruptedException e) {e.printStackTrace();}}
}class DiningPhilosophers {public static void main(String[] args) {int numPhilosophers = 5;Philosopher[] philosophers = new Philosopher[numPhilosophers];Lock[] forks = new ReentrantLock[numPhilosophers];for (int i = 0; i < numPhilosophers; i++) {forks[i] = new ReentrantLock();}for (int i = 0; i < numPhilosophers; i++) {philosophers[i] = new Philosopher(i, forks[i], forks[(i + 1) % numPhilosophers]);philosophers[i].start();}// 等待所有哲学家线程结束for (Philosopher philosopher : philosophers) {try {philosopher.join();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println("All philosophers have finished eating. Program ends.");}
}

  使用ReentrantLock锁, 该类中有一个tryLock()方法, 在指定时间内获取不到锁对象, 就从阻塞队列移除,不用一直等待。当获取了左手边的筷子之后, 尝试获取右手边的筷子, 如果该筷子被其他哲学家占用, 获取失败, 此时就先把自己左手边的筷子给释放掉. 这样就避免了死锁问题

 方法三

奇数哲学家先左后右,偶数科学家先右后左
import java.util.concurrent.Semaphore;public class 方法四 {//奇数哲学家先左后右,偶数科学家先右后左// Five forksstatic final Semaphore[] mutex = { new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1) };static class Philosopher extends Thread {Philosopher(int name) {super.setName(String.valueOf(name));}@Overridepublic void run() {do {try {Integer i = Integer.parseInt(super.getName());if (i % 2 == 1) {// Odd-numbered philosopher// Try to acquire the left forkmutex[i].acquire();System.out.println("哲学家" + i + "号拿起左筷子");// Try to acquire the right forkmutex[(i + 1) % 5].acquire();System.out.println("哲学家" + i + "号拿起右筷子");} else {// Even-numbered philosopher// Try to acquire the right forkmutex[(i + 1) % 5].acquire();System.out.println("哲学家" + i + "号拿起右筷子");// Try to acquire the left forkmutex[i].acquire();System.out.println("哲学家" + i + "号拿起左筷子");}// EatSystem.out.println("哲学家" + i + "号吃饭!");// Release the forksmutex[i].release();mutex[(i + 1) % 5].release();// Think (sleep for simulation)Thread.sleep(2000);} catch (InterruptedException e) {System.out.println("异常");}} while (true);}}public static void main(String[] args) {Philosopher[] threads = new Philosopher[5];for (int i = 0; i < 5; i++) {threads[i] = new Philosopher(i);}for (Philosopher i : threads) {i.start();}}
}

下面是将think和eat分开的版本:

import java.util.concurrent.Semaphore;
public class 方法四改进 {public static class 方法四 {//奇数哲学家先左后右,偶数科学家先右后左// Five forksstatic final Semaphore[] mutex = { new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1),new Semaphore(1) };static class Philosopher extends Thread {Philosopher(int name) {super.setName(String.valueOf(name));}@Overridepublic void run() {do {try {think();eat();} catch (InterruptedException e) {System.out.println("异常");}} while (true);}public void think() throws InterruptedException {Integer i = Integer.parseInt(super.getName());System.out.println("哲学家" + i + "号正在思考");// Think (sleep for simulation)Thread.sleep(2000);}public void eat() throws InterruptedException {Integer i = Integer.parseInt(super.getName());if (i % 2 == 1) {// Odd-numbered philosopher// Try to acquire the left forkmutex[i].acquire();System.out.println("哲学家" + i + "号拿起左筷子");// Try to acquire the right forkmutex[(i + 1) % 5].acquire();System.out.println("哲学家" + i + "号拿起右筷子");} else {// Even-numbered philosopher// Try to acquire the right forkmutex[(i + 1) % 5].acquire();System.out.println("哲学家" + i + "号拿起右筷子");// Try to acquire the left forkmutex[i].acquire();System.out.println("哲学家" + i + "号拿起左筷子");}// EatSystem.out.println("哲学家" + i + "号吃饭!");// Release the forksmutex[i].release();mutex[(i + 1) % 5].release();}}public static void main(String[] args) {Philosopher[] threads = new Philosopher[5];for (int i = 0; i < 5; i++) {threads[i] = new Philosopher(i);}for (Philosopher i : threads) {i.start();}}}}

这篇关于哲学家就餐问题(java全代码)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/418038

相关文章

Java对象和JSON字符串之间的转换方法(全网最清晰)

《Java对象和JSON字符串之间的转换方法(全网最清晰)》:本文主要介绍如何在Java中使用Jackson库将对象转换为JSON字符串,并提供了一个简单的工具类示例,该工具类支持基本的转换功能,... 目录前言1. 引入 Jackson 依赖2. 创建 jsON 工具类3. 使用示例转换 Java 对象为

解读为什么@Autowired在属性上被警告,在setter方法上不被警告问题

《解读为什么@Autowired在属性上被警告,在setter方法上不被警告问题》在Spring开发中,@Autowired注解常用于实现依赖注入,它可以应用于类的属性、构造器或setter方法上,然... 目录1. 为什么 @Autowired 在属性上被警告?1.1 隐式依赖注入1.2 IDE 的警告:

SpringBoot快速接入OpenAI大模型的方法(JDK8)

《SpringBoot快速接入OpenAI大模型的方法(JDK8)》本文介绍了如何使用AI4J快速接入OpenAI大模型,并展示了如何实现流式与非流式的输出,以及对函数调用的使用,AI4J支持JDK8... 目录使用AI4J快速接入OpenAI大模型介绍AI4J-github快速使用创建SpringBoot

Java中的Cursor使用详解

《Java中的Cursor使用详解》本文介绍了Java中的Cursor接口及其在大数据集处理中的优势,包括逐行读取、分页处理、流控制、动态改变查询、并发控制和减少网络流量等,感兴趣的朋友一起看看吧... 最近看代码,有一段代码涉及到Cursor,感觉写法挺有意思的。注意是Cursor,而不是Consumer

解决java.lang.NullPointerException问题(空指针异常)

《解决java.lang.NullPointerException问题(空指针异常)》本文详细介绍了Java中的NullPointerException异常及其常见原因,包括对象引用为null、数组元... 目录Java.lang.NullPointerException(空指针异常)NullPointer

javaScript在表单提交时获取表单数据的示例代码

《javaScript在表单提交时获取表单数据的示例代码》本文介绍了五种在JavaScript中获取表单数据的方法:使用FormData对象、手动提取表单数据、使用querySelector获取单个字... 方法 1:使用 FormData 对象FormData 是一个方便的内置对象,用于获取表单中的键值

Vue ElementUI中Upload组件批量上传的实现代码

《VueElementUI中Upload组件批量上传的实现代码》ElementUI中Upload组件批量上传通过获取upload组件的DOM、文件、上传地址和数据,封装uploadFiles方法,使... ElementUI中Upload组件如何批量上传首先就是upload组件 <el-upl

前端知识点之Javascript选择输入框confirm用法

《前端知识点之Javascript选择输入框confirm用法》:本文主要介绍JavaScript中的confirm方法的基本用法、功能特点、注意事项及常见用途,文中通过代码介绍的非常详细,对大家... 目录1. 基本用法2. 功能特点①阻塞行为:confirm 对话框会阻塞脚本的执行,直到用户作出选择。②

SpringBoot项目注入 traceId 追踪整个请求的日志链路(过程详解)

《SpringBoot项目注入traceId追踪整个请求的日志链路(过程详解)》本文介绍了如何在单体SpringBoot项目中通过手动实现过滤器或拦截器来注入traceId,以追踪整个请求的日志链... SpringBoot项目注入 traceId 来追踪整个请求的日志链路,有了 traceId, 我们在排

Java实战之利用POI生成Excel图表

《Java实战之利用POI生成Excel图表》ApachePOI是Java生态中处理Office文档的核心工具,这篇文章主要为大家详细介绍了如何在Excel中创建折线图,柱状图,饼图等常见图表,需要的... 目录一、环境配置与依赖管理二、数据源准备与工作表构建三、图表生成核心步骤1. 折线图(Line Ch