哲学家就餐问题(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

相关文章

Kotlin Map映射转换问题小结

《KotlinMap映射转换问题小结》文章介绍了Kotlin集合转换的多种方法,包括map(一对一转换)、mapIndexed(带索引)、mapNotNull(过滤null)、mapKeys/map... 目录Kotlin 集合转换:map、mapIndexed、mapNotNull、mapKeys、map

nginx中端口无权限的问题解决

《nginx中端口无权限的问题解决》当Nginx日志报错bind()to80failed(13:Permissiondenied)时,这通常是由于权限不足导致Nginx无法绑定到80端口,下面就来... 目录一、问题原因分析二、解决方案1. 以 root 权限运行 Nginx(不推荐)2. 为 Nginx

SpringBoot中六种批量更新Mysql的方式效率对比分析

《SpringBoot中六种批量更新Mysql的方式效率对比分析》文章比较了MySQL大数据量批量更新的多种方法,指出REPLACEINTO和ONDUPLICATEKEY效率最高但存在数据风险,MyB... 目录效率比较测试结构数据库初始化测试数据批量修改方案第一种 for第二种 case when第三种

解决1093 - You can‘t specify target table报错问题及原因分析

《解决1093-Youcan‘tspecifytargettable报错问题及原因分析》MySQL1093错误因UPDATE/DELETE语句的FROM子句直接引用目标表或嵌套子查询导致,... 目录报js错原因分析具体原因解决办法方法一:使用临时表方法二:使用JOIN方法三:使用EXISTS示例总结报错原

Java docx4j高效处理Word文档的实战指南

《Javadocx4j高效处理Word文档的实战指南》对于需要在Java应用程序中生成、修改或处理Word文档的开发者来说,docx4j是一个强大而专业的选择,下面我们就来看看docx4j的具体使用... 目录引言一、环境准备与基础配置1.1 Maven依赖配置1.2 初始化测试类二、增强版文档操作示例2.

一文详解如何使用Java获取PDF页面信息

《一文详解如何使用Java获取PDF页面信息》了解PDF页面属性是我们在处理文档、内容提取、打印设置或页面重组等任务时不可或缺的一环,下面我们就来看看如何使用Java语言获取这些信息吧... 目录引言一、安装和引入PDF处理库引入依赖二、获取 PDF 页数三、获取页面尺寸(宽高)四、获取页面旋转角度五、判断

Windows环境下解决Matplotlib中文字体显示问题的详细教程

《Windows环境下解决Matplotlib中文字体显示问题的详细教程》本文详细介绍了在Windows下解决Matplotlib中文显示问题的方法,包括安装字体、更新缓存、配置文件设置及编码調整,并... 目录引言问题分析解决方案详解1. 检查系统已安装字体2. 手动添加中文字体(以SimHei为例)步骤

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命