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

相关文章

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注

Spring事务传播机制最佳实践

《Spring事务传播机制最佳实践》Spring的事务传播机制为我们提供了优雅的解决方案,本文将带您深入理解这一机制,掌握不同场景下的最佳实践,感兴趣的朋友一起看看吧... 目录1. 什么是事务传播行为2. Spring支持的七种事务传播行为2.1 REQUIRED(默认)2.2 SUPPORTS2

怎样通过分析GC日志来定位Java进程的内存问题

《怎样通过分析GC日志来定位Java进程的内存问题》:本文主要介绍怎样通过分析GC日志来定位Java进程的内存问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、GC 日志基础配置1. 启用详细 GC 日志2. 不同收集器的日志格式二、关键指标与分析维度1.

Java进程异常故障定位及排查过程

《Java进程异常故障定位及排查过程》:本文主要介绍Java进程异常故障定位及排查过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、故障发现与初步判断1. 监控系统告警2. 日志初步分析二、核心排查工具与步骤1. 进程状态检查2. CPU 飙升问题3. 内存

java中新生代和老生代的关系说明

《java中新生代和老生代的关系说明》:本文主要介绍java中新生代和老生代的关系说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、内存区域划分新生代老年代二、对象生命周期与晋升流程三、新生代与老年代的协作机制1. 跨代引用处理2. 动态年龄判定3. 空间分

Java设计模式---迭代器模式(Iterator)解读

《Java设计模式---迭代器模式(Iterator)解读》:本文主要介绍Java设计模式---迭代器模式(Iterator),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录1、迭代器(Iterator)1.1、结构1.2、常用方法1.3、本质1、解耦集合与遍历逻辑2、统一

Java内存分配与JVM参数详解(推荐)

《Java内存分配与JVM参数详解(推荐)》本文详解JVM内存结构与参数调整,涵盖堆分代、元空间、GC选择及优化策略,帮助开发者提升性能、避免内存泄漏,本文给大家介绍Java内存分配与JVM参数详解,... 目录引言JVM内存结构JVM参数概述堆内存分配年轻代与老年代调整堆内存大小调整年轻代与老年代比例元空

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

Java 线程安全与 volatile与单例模式问题及解决方案

《Java线程安全与volatile与单例模式问题及解决方案》文章主要讲解线程安全问题的五个成因(调度随机、变量修改、非原子操作、内存可见性、指令重排序)及解决方案,强调使用volatile关键字... 目录什么是线程安全线程安全问题的产生与解决方案线程的调度是随机的多个线程对同一个变量进行修改线程的修改操