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

📄 diningphilosophers.java

📁 Java 程序设计源码 只提供了部分
💻 JAVA
字号:
import java.util.*;//定义 超时类class Timeout extends Timer {  public Timeout(int delay, final String msg) {    super(true);    super.schedule(        new TimerTask() {          public void run() {            System.out.println(msg);          }        }, delay);  }}//Chopstick 类 的 定义class Chopstick {  //static 全局变量  private static int counter = 0;  private int number = counter++;  public String toString() {    return "Chop " + number;  }}class Philosopher extends Thread {  //产生 随机 时间 作为 Philosopher 的思考时间  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() {    //this 代表 Philosopher    System.out.println(this + " thinking");    if(ponder > 0) {      try {        //睡眠 ponder 毫秒 相当于 思考        sleep(rand.nextInt(ponder));      }      catch(InterruptedException e) {        throw new RuntimeException(e);      }    }  }  public void eat() {    //同步左边的 Chopstick    synchronized(leftChopstick) {      System.out.println(this + " has " + this.leftChopstick + " waiting "          + this.rightChopstick);      synchronized(rightChopstick) {        System.out.println(this + " is eatting.");      }    }  }  public String toString() {    return "Philosopher " + number;  }  public void run() {    while(true) {      think();      eat();    }  }}public class DiningPhilosophers {  public static void main(String[] args) {    if(args.length < 3) {      System.err.println("use method: \n" + "Philosopher number " + "thinking time\n");      System.exit(0);    }    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("DeadLock")) {      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, "time over");      }    }  }}

⌨️ 快捷键说明

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