📄 dining.java
字号:
class Chopstick
{
boolean available;
Chopstick()
{
available=true;
}
public synchronized void takeup()
{
while(!available)
{
try
{
System.out.println("哲学家在等待另一根筷子");
wait();
}
catch(InterruptedException e){}
}
available=false;
}
public synchronized void putdown()
{
available=true;
notify();
}
}
class Philosopher extends Thread
{
Chopstick left,right;
int p_num;
Philosopher(int num,Chopstick c1,Chopstick c2)
{
p_num=num;
left=c1;
right=c2;
}
public void eat()
{
left.takeup();
right.takeup();
System.out.println("哲学家"+(p_num+1)+" 正在进餐");
}
public void think()
{
left.putdown();
right.putdown();
System.out.println("哲学家"+(p_num+1)+" 正在思考");
}
public void run()
{
while(true)
{
eat();
try{sleep(1000);}
catch(InterruptedException e){}
think();
try{sleep(1000);}
catch(InterruptedException e){}
}
}
}
public class Dining
{
static Chopstick[] cs=new Chopstick[5];
static Philosopher[] ps=new Philosopher[5];
public static void main(String[] args)
{
for(int i=0;i<5;i++)
{cs[i]=new Chopstick();}
for(int i=0;i<5;i++)
{ps[i]=new Philosopher(i,cs[i],cs[(i+1)%5]);}
for(int i=0;i<5;i++)
{ps[i].start();}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -