某次操作系统实验存档。
这个哲学家除了吃就是睡。。
哲学家.java:
package operating.entity.philosophyeating; import operating.method.Semaphore; import java.util.Date; public class Philosophy implements Runnable {
/**
* 统计哲学家数量
*/
private static int total = 0;
/**
* 哲学家的 id
*/
private int id;
private Semaphore leftChopsticks;
private Semaphore rightChopsticks;
/**
* 记住睡眠时间
*/
private Long sleepTime; public Philosophy(Semaphore leftChopsticks, Semaphore rightChopsticks) {
id = total++;
sleepTime = new Date().getTime();
this.leftChopsticks = leftChopsticks;
this.rightChopsticks = rightChopsticks;
} @Override
public void run() {
while(true) {
if(id % 2 == 0) {
leftChopsticks.p();
rightChopsticks.p(); System.out.println("number " + id + " philosophy is eating, yummy..." + "睡眠 " + endSleep() + "秒。");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
beginSleep(); rightChopsticks.v();
leftChopsticks.v();
} else {
rightChopsticks.p();
leftChopsticks.p(); System.out.println("number " + id + " philosophy is eating, yummy..." + "睡眠 " + endSleep() + "秒。");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
beginSleep(); leftChopsticks.v();
rightChopsticks.v();
}
}
} /**
* 开始睡眠
*/
public void beginSleep() {
sleepTime = new Date().getTime();
} /**
* 结束睡眠,返回睡眠时间,单位是秒。
* @return
*/
public Long endSleep() {
return (new Date().getTime() - sleepTime)/1000;
}
}
测试.java:
package operating.test; import operating.entity.philosophyeating.Philosophy;
import operating.method.Semaphore; public class PhilosophyTest {
public static void main(String[] args) {
// 创建六支筷子
Semaphore[] chopsticks = new Semaphore[6];
for (int i = 0; i != 6; ++i) {
chopsticks[i] = new Semaphore(1);
} // 创建六个哲学家
for (int i = 0; i != 6; ++i) {
if (i == 5) {
new Thread(new Philosophy(chopsticks[i], chopsticks[0])).start();
} else {
new Thread(new Philosophy(chopsticks[i], chopsticks[i+1])).start();
}
}
}
}
/