?? diningphilosophers.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 + -