编程实现哲学家就餐问题(java)
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
编程实现哲学家就餐问题。
import java.util.Random;
public class Philosoper extends Thread {
private String name;
private ChopStick leftCS;
private ChopStick rightCS;
public Philosoper(String name, ChopStick leftCS, ChopStick rightCS) { = name;
this.leftCS = leftCS;
this.rightCS = rightCS;
}
public void run() {
try {
sleep(Random.class.newInstance().nextInt(100));
} catch (Exception e) {
e.printStackTrace();
}
synchronized (leftCS) {
System.out.println( + "has the left chopstick "
+ leftCS.getName() + "and wait right one"
+ rightCS.getName() + "...");
synchronized (rightCS) {
System.out.println( + "get right chopstick "
+ rightCS.getName() + " begin to eat!");
}
}
}
class ChopStick {
private String name;
public ChopStick(String name) {
= name;
}
public String getName() {
return name;
}
}
public static void main(String[] args) {
ChopStick cs1 = new ChopStick("cs1");
ChopStick cs2 = new ChopStick("cs2");
ChopStick cs3 = new ChopStick("cs3");
Philosoper p1 = new Philosoper("p1", cs1, cs2);
Philosoper p2 = new Philosoper("p2", cs2, cs3);
Philosoper p3 = new Philosoper("p3", cs3, cs1);
p1.start();
p2.start();
p3.start();
}
}