哲学家就餐问题

/**
 * 哲学家用餐问题:有五个哲学家共用一张圆桌,分别坐在周围的五张椅子上,在圆桌上有五个碗和
 *五只筷子,他们的生活方式是交替地进行思考和进餐。平时,一个哲学家进行思考,饥饿的时候变
 *试图取用其左右靠近他的筷子,只有在拿起两只筷子时才能进餐。进餐完毕,放下筷子继续思考
 */

 

/**
 * 筷子类
 */
class Chopstick {
       private boolean available; // 筷子的状态

       public Chopstick() {
           this.available = true; // 默认设置筷子状态为放下的(即可用的)
       }

 

      /**
      * 拿起筷子方法 将筷子的状态设置为false(即不可用),若已经为false,则进入阻塞队列中自我阻塞
      */
 public synchronized void takeUp() {
     while (!available) {
            System.out.println("此筷子正在被使用中,哲学家在等待筷子。。。");
      try {
            this.wait(); // 阻塞
          } catch (InterruptedException e) {
             e.printStackTrace();
          }
  }


  this.available = false;

 }

 

 /**
  * 放下筷子方法 将筷子的状态设置为true(可用),唤醒阻塞队列中的一个线程
  */
 public synchronized void putDown() {
  this.available = true;
  this.notify();
 }
}

/**
 * 哲学家类
  */
class Philosopher extends Thread {

 private Chopstick leftChopstick, rightChopstick; // 左右筷子
 private int philosopherNum; // 哲学家序号

 public Philosopher() {
 }

 public Philosopher(int philosopherNum, Chopstick leftChopstick,
   Chopstick rightChopstick) {
  this.leftChopstick = leftChopstick;
  this.rightChopstick = rightChopstick;
  this.philosopherNum = philosopherNum;
 }

 /**
  * 哲学家就餐方法,只有拿到左右两只筷子时才能进餐
  */
 public void eat() {
  leftChopstick.takeUp();
  rightChopstick.takeUp();
  System.out.println("哲学家" + philosopherNum + "正在进餐...");
 }

 /**
  * 哲学家思考方法,放下左右两只筷子进行思考
  */
 public void think() {
  leftChopstick.putDown();
  rightChopstick.putDown();
  System.out.println("哲学家" + philosopherNum + "正在思考...");
 }

 /**
  * run方法,哲学家进餐与思考中
  */
 public void run() {
  while (true) {
   this.eat();
   try {
    Thread.currentThread().sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
   this.think();
   try {
    Thread.currentThread().sleep(1000);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }

}

/**
 * 主调函数,创建5只筷子和5个哲学家,执行run方法
 */
public class DiningPhilosopherProblem {
 static Chopstick[] chopsticks = new Chopstick[5];
 static Philosopher[] philosophers = new Philosopher[5];

 public static void main(String[] args) {
  // 创建5只筷子对象
  for (int i = 0; i < chopsticks.length; i++) {
   chopsticks[i] = new Chopstick();
  }
  // 创建5个哲学家对象
  for (int i = 0; i < philosophers.length; i++) {
   philosophers[i] = new Philosopher(i, chopsticks[i],
     chopsticks[(i + 1) % 5]);
  }
  // 启动线程
  for (int i = 0; i < philosophers.length; i++) {
   philosophers[i].start();
  }

 }
}
运行结果:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值