哲学家吃饭
问题(JAVA实现)
import java.util.*; //包含
常用的数据类型类
public class DishWare
{
private String name;
public DishWare(String name)
{
this.name=name;
}
public String getNumber()
{
return name;
}
}
//Philospher.java
class Philospher extends Thread
{
private DishWare Knife;
private DishWare Fork;
private String name;
private static Random random=new Random();
public Philospher(String name,DishWare Knife,DishWare Fork) //构造函数,变量初始化
{
this.name=name;
this.Knife=Knife;
this.Fork=Fork;
}
public String getNumber()
{
return name;
}
public void run() //多线程的实现方法run()
{
try{
sleep(random.nextInt(3));
}
catch(InterruptedException e){}
synchronized(Knife)
{ //线程的同步,使用synchronized关键词
System.out.println(this.getNumber()+" has "+Knife.getNumber()+" and wait for "+Fork.getNumber());
synchronized(Fork){
System.out.println(this.getNumber()+" eating");
}
}
}
public static void main(String args[])
{
//建立刀叉对象
DishWare knife1=new DishWare("Knife1");
DishWare fork1=new DishWare("Fork1");
DishWare knife2=new DishWare("Knife2");
DishWare fork2=new DishWare("Fork2");
//建立哲学家对象,并在其两边摆放刀叉
Philospher philospher1=new Philospher("philospher1",knife1,fork1);
Philospher philospher2=new Philospher("philospher2",fork1,knife2);
Philospher philospher3=new Philospher("philospher3",knife2,fork2);
Philospher philospher4=new Philospher("philospher4",fork2,knife1);
//启动3个线程,用start方法开始线程
philospher1.start();
philospher2.start();
philospher3.start();
philospher4.start();
}
}