JavaSE(线程问题)哲学家与筷子问题

哲学家类:

public class Philosopher extends Thread {
 int number;
 Chopsticks chop;
 private String name;
 //定义无参构造
 public Philosopher(){
  
 }
 //定义带参构造
 public Philosopher(int number,Chopsticks chop){
  this.number = number;
  this.chop = chop;
 }
 //重写run方法
 public void run(){
   while(true){
    chop.takeup();    
    eating();
    chop.putdown();
    thinking();
  }
 }
 //哲学家进餐方法
 public void eating(){
  System.out.println("哲学家"+Thread.currentThread().getName()+"正在进餐");
  try{
   Thread.sleep((int)(Math.random()*10000));
  }catch(InterruptedException e){
   
  }
 }
 //哲学家思考方法
 public void thinking(){
  System.out.println("哲学家"+Thread.currentThread().getName()+"进餐毕,正在思考");
  try{
  Thread.sleep((int)(Math.random()*1000));
  }catch(InterruptedException e){
   
  }
 }
 public static void main(String[] args) {
  Chopsticks chop = new Chopsticks();  
  for(int j=0;j<5;j++)  
   new Philosopher(j,chop).start();    
 }

}

筷子类:

public class Chopsticks {

private int s[]={0,0,0,0,0};
 public synchronized void takeup(){
  int i = Integer.parseInt(Thread.currentThread().getName().substring(7));
  int j = i-1;
  if(i==0){
   j = i;
   i = 4;
  }
  while(s[i]==1){
   try{
    wait();
   }catch(InterruptedException e){
    
   }
  }
  s[i]=1;
  while(s[j]==1){
   try{
    wait();
   }catch(InterruptedException e){
    
   }
  }
  s[j]=1;
 } 
 public synchronized void putdown(){
  int i = Integer.parseInt(Thread.currentThread().getName().substring(7));
  s[i]=0;
  s[(i+1)%5]=0;
  notifyAll();
 }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值