1.AND型信号量
(1)Chopsticks.java**
package philosopy;
import java util.*;
class Chopsticks {
public static List chops = new ArrayList();
static {
chops.add(false); //为了方便计算,第一个不会参与计算
chops.add(false);
chops.add(false);
chops.add(false);
chops.add(false);
}
public synchronized void getChop() {
String currentName = Thread.currentThread().getName();
int index = Integer.parseInt(currentName);
while (chops.get(index) || chops.get((index + 1)%5)) {//同时获得两双筷子才能进行
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
chops.set(index, true);
chops.set((index + 1)%5 ,true);
}
public synchronized void freeChop() {
String currentName = Thread.currentThread().getName();
int index = Integer.parseInt(currentName);
chops.set(index, false);//释放左筷子
chops.set((index + 1)%5 ,false);//释放右筷子
notifyAll();//通知所有人我已吃完
}
}
(2)PhilosopherThread.java类
class PhilosopherThread extends Thread {
private String name; //线程名称,给哲学家编序号用
private Chopsticks chopsticks;
public PhilosopherThread (String name, Chopsticks chopsticks) {