⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 diningphilosophers.java

📁 180个针对Java初学者的简单实例180个针对Java初学者的简单实例180个针对Java初学者的简单实例
💻 JAVA
字号:
import java.util.*;

class Timeout extends Timer {
  public Timeout(int delay, final String msg) {
    super(true); // 守护线程
    schedule(new TimerTask() {
      public void run() {
        System.out.println(msg);
        System.exit(0);
      }
    }, delay);
  }
}
class Chopstick {
  private static int counter = 0;
  private int number = counter++;
  public String toString() {
    return "筷子 " + number;
  }
}
class Philosopher extends Thread {
  private static Random rand = new Random();
  private static int counter = 0;
  private int number = counter++;
  private Chopstick leftChopstick;
  private Chopstick rightChopstick;
  static int ponder = 0; 
  public Philosopher(Chopstick left, Chopstick right) {
    leftChopstick = left;
    rightChopstick = right;
    start();
  }
  public void think() {
    System.out.println(this + " 在思考");
    if(ponder > 0)
      try {
        sleep(rand.nextInt(ponder));
      } catch(InterruptedException e) {
        throw new RuntimeException(e);
      }
  }
  public void eat() {
    synchronized(leftChopstick) {
      System.out.println(this + " 有 "
        + this.leftChopstick + " 等待 "
        + this.rightChopstick);
      synchronized(rightChopstick) {
        System.out.println(this + " 在吃饭");
      }
    }
  }
  public String toString() {
    return "哲学家 " + number;
  }
  public void run() {
    while(true) {
      think();
      eat();
    }
  }
}
public class DiningPhilosophers {
  public static void main(String[] args) {
    if(args.length < 3) {
      System.err.println("使用方法:\n" +
        "进餐的哲学家人数 " +
        "思考时间\n" );
      System.exit(1);
    }
    Philosopher[] philosopher =
      new Philosopher[Integer.parseInt(args[0])];
    Philosopher.ponder = Integer.parseInt(args[1]);
    Chopstick
      left = new Chopstick(),
      right = new Chopstick(),
      first = left;
    int i = 0;
    while(i < philosopher.length - 1) {
      philosopher[i++] =
        new Philosopher(left, right);
      left = right;
      right = new Chopstick();
    }
    if(args[2].equals("死锁"))
      philosopher[i] = new Philosopher(left, first);
    else // 转换值防止死锁的发生
      philosopher[i] = new Philosopher(first, left);
    // 有选择的退出程序
    if(args.length >= 4) {
      int delay = Integer.parseInt(args[3]);
      if(delay != 0)
        new Timeout(delay * 1000, "时间用完");
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -