java 哲学家_java 哲学家就餐问题 实例源码

这是一个Java编程示例,展示了如何实现哲学家就餐问题。每个哲学家由Philosopher类表示,使用ChopstickArray对象来模拟筷子。哲学家在思考和吃饭之间切换,当他们想吃饭时会检查并获取左右两边的筷子,如果筷子不可用,则进入等待状态。程序通过线程同步控制哲学家的行为,避免出现死锁情况。
摘要由CSDN通过智能技术生成

【实例简介】

【实例截图】

13bb7f899e4473b9291bd3afaee1ff8c.png

【核心代码】

package com.mingrisoft;

import java.util.Random;

import javax.swing.JTextArea;

public class Philosopher implements Runnable {

private int id;

private ChopstickArray chopstickArray;

private boolean state;

private JTextArea thinkingTextArea;

private JTextArea eatingTextArea;

private JTextArea waitingTextArea;

public Philosopher(int id, ChopstickArray chopstickArray, JTextArea thinkingTextArea, JTextArea eatingTextArea, JTextArea waitingTextArea) {

this.id = id;

this.chopstickArray = chopstickArray;

this.thinkingTextArea = thinkingTextArea;

this.eatingTextArea = eatingTextArea;

this.waitingTextArea = waitingTextArea;

}

public synchronized void thinking() {

if (state) {

chopstickArray.get(id).setAvailable(true);

chopstickArray.getLast(id).setAvailable(true);

String text = thinkingTextArea.getText();

thinkingTextArea.setText(text this " 在思考\n");

try {

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

state = false;

}

public synchronized void eating() {

if (!state) {// state是一个布尔值,true表示哲学家刚才的状态是吃饭,false表示思考

if (chopstickArray.get(id).isAvailable()) {// 如果哲学家右手边的筷子可用

if (chopstickArray.getLast(id).isAvailable()) {// 如果哲学家左手边的筷子可用

chopstickArray.get(id).setAvailable(false);// 设置右手筷子不可用

chopstickArray.getLast(id).setAvailable(false);// 设置左手筷子不可用

String text = eatingTextArea.getText();

eatingTextArea.setText(text this " 在吃饭\n");// 显示哲学家在吃饭

try {

Thread.sleep(100);// 吃饭时间设置成0.1秒

} catch (InterruptedException e) {

e.printStackTrace();

}

} else {// 如果哲学家左手边的筷子不可用,就在相应的文本域中显示等待信息

String text = waitingTextArea.getText();

waitingTextArea.setText(text this " 在等待 " chopstickArray.getLast(id) "\n");

try {

wait(new Random().nextInt(100));// 等待小于0.1秒时间后检查筷子是否可用

} catch (InterruptedException e) {

e.printStackTrace();

}

}

} else {// 如果哲学家右手边的筷子不可用,就在相应的文本域中显示等待信息

String text = waitingTextArea.getText();

waitingTextArea.setText(text this " 在等待 " chopstickArray.get(id) "\n");

try {

wait(new Random().nextInt(100));// 等待小于0.1秒时间后检查筷子是否可用

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

state = true;// 设置state的值为true表示哲学家的状态是吃饭

}

@Override

public void run() {

for (int i = 0; i < 10; i ) {

thinking();

eating();

}

}

@Override

public String toString() {

return " 哲学家 " id;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值