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