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

📄 philosopher.java

📁 升级版本
💻 JAVA
字号:
import java.util.Random;import org.jcsp.lang.CSProcess;import org.jcsp.lang.CSTimer;import org.jcsp.lang.ChannelOutput;import org.jcsp.lang.Parallel;import org.jcsp.plugNplay.ProcessWrite;class Philosopher implements CSProcess {  // protected attributes  protected final static int seconds = 1000;  protected final static int maxThink = 10*seconds;  protected final static int maxEat = 15*seconds;  protected final static String[] space =    {"  ", "    ", "      ", "        ", "          "};  protected final int id;  protected final ChannelOutput left, right, down, up;  protected final ChannelOutput report;  protected final Random random;  // constructors  public Philosopher (int id, ChannelOutput left, ChannelOutput right,                      ChannelOutput down, ChannelOutput up,                      ChannelOutput report) {    this.id = id;    this.left = left;    this.right = right;    this.down = down;    this.up = up;    this.report = report;    this.random = new Random (id + 1);  }  // public methods  public void run () {    final Integer Id = new Integer (id);    final CSTimer tim = new CSTimer ();    final PhilReport thinking = new PhilReport (id, PhilReport.THINKING);    final PhilReport hungry = new PhilReport (id, PhilReport.HUNGRY);    final PhilReport sitting = new PhilReport (id, PhilReport.SITTING);    final PhilReport eating= new PhilReport (id, PhilReport.EATING);    final PhilReport leaving = new PhilReport (id, PhilReport.LEAVING);    final ProcessWrite signalLeft = new ProcessWrite (left);    signalLeft.value = Id;    final ProcessWrite signalRight = new ProcessWrite (right);    signalRight.value = Id;    final Parallel signalForks = new Parallel (new CSProcess[] {signalLeft, signalRight});    while (true) {      report.write (thinking);      tim.sleep (range (maxThink));    // thinking      report.write (hungry);      down.write (Id);                 // get past the security guard      report.write (sitting);      signalForks.run ();              // pick up my forks (in parallel)      report.write (eating);      tim.sleep (range (maxEat));      // eating      report.write (leaving);      signalForks.run ();              // put down my forks (in parallel)      up.write (Id);                   // get up from the table and go past the security guard    }  }  // protected methods  protected int range (int n) {    // returns random int in the range 0 .. (n - 1)  [This is not needed in JDK 1.2.x]    int i = random.nextInt ();    if (i < 0) {      if (i == Integer.MIN_VALUE) {        i = 42;      } else {        i = -i;      }    }    return i % n;  }}

⌨️ 快捷键说明

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