全国
Java--教育路上

栏目导航

全国站 > Java > 多线程
需求

java哲学家进餐模拟

摘要:java哲学家进餐模拟,哲学家进餐问题描述有五个哲学家,java 哲学家 进餐 模拟。以下是我们为大家整理的,相信大家阅读完后肯定有了自己的选择吧。

标签:
发布时间:
2024-05-02 11:12
信息来源:
网络推荐
浏览次数:
612
java哲学家进餐模拟

任务介绍:n 哲学家进餐问题描述有五个哲学家,他们的生活方式是交替地进行思考和进餐,

n 哲学家们共用一张圆桌,分别坐在周围的五张椅子上,在圆桌上有五个碗和五支筷子,n

平时哲学家进行思考,饥饿时便试图取其左、右最靠近他的筷子,只有在他拿到两支筷子时

才能进餐,n 进餐完毕,放下筷子又继续思考。

任务目标:掌握多线程编程,掌握信号量机制

实现思路:哲学家问题的约束条件为:1、只有拿到两只筷子时,哲学家才能吃饭。 2、如

果筷子已被别人拿走,则必须等别人吃完之后才能拿到筷子。3、任一哲学家在自己未拿到

两只筷子吃饭前,不会放下手中拿到的筷子。筷子是临界资源,一段时间只允许一位哲学家

使用。为了表示互斥,用一个信号量表示一只筷子,五个信号量构成信号量数组。

from shengerguan

实现代码

Chopstick.java

public class Chopstick {

int num;

public Chopstick(int num)

{

this.num=num;

}

public String printName()

{

return "第"+num+"只筷子";

}

}

Philosopher.java

public class Philosopher implements Runnable {

int num;

Chopstick leftChopstick;

Chopstick rightChopstick;

public Philosopher(int num,Chopstick left,Chopstick right)

{

this.num=num;

leftChopstick=left;

rightChopstick=right;

}

public void run() {

while(true)

{

synchronized(leftChopstick)

{

System.out.println(num+"号哲学家获得了左手边的筷子,即

"+leftChopstick.printName());

synchronized (rightChopstick) {

System.out.println(num+"号哲学家获得了右手边的筷子,即

"+rightChopstick.printName());

System.out.println(num+"号哲学家开始进餐。");

try {

Thread.sleep(2000);

}

catch (InterruptedException e) {

// TODO: handle exception

e.printStackTrace();

}

System.out.println(num+"号哲学家进餐完毕,放下右手边筷子

"+rightChopstick.printName());

}

System.out.println(num+"号哲学家进餐完毕,放下左手边筷子

"+leftChopstick.printName());

}

System.out.println(num+"号哲学家进餐完毕,开始思考问题。");

try {

Thread.sleep(2000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

Example03.java

public class Example03 {

public static void main(String[] args) {

// TODO Auto-generated method stub

Chopstick ct1,ct2,ct3,ct4,ct5;

ct1=new Chopstick(1);

ct2=new Chopstick(2);

ct3=new Chopstick(3);

ct4=new Chopstick(4);

ct5=new Chopstick(5);

Philosopher ps1=new Philosopher(1, ct1, ct2);

Philosopher ps2=new Philosopher(2, ct2, ct3);

Philosopher ps3=new Philosopher(3, ct3, ct4);

Philosopher ps4=new Philosopher(4, ct4, ct5);

Philosopher ps5=new Philosopher(5, ct1, ct5);

new Thread(ps1).start();

new Thread(ps2).start();

new Thread(ps3).start();

new Thread(ps4).start();

new Thread(ps5).start();

}

}


上一篇:
java编写一个程序在窗体中模拟..
下一篇:
java线程概述
相关推荐
最近更新
学校免费发布信息关闭
如有图片请发邮件到:edu63@foxmail.com,审核后显示

 换一张

确认提交
完善补充本文信息关闭
非常感谢您帮助完善补充本文信息


 换一张

确认提交