我在完成家庭作业时遇到了麻烦,因此在经过数小时的尝试和谷歌搜索后,我除了寻求其他帮助外别无选择。我有这段代码(不是整个程序,也有一些类和数据包以图形方式模拟了此代码的工作方式,但我认为不必在此处发布它):
public class KidsAndTramboline {
private Tramboline tramboline = new Tramboline(300, 5);
private class Tramboline {
private Semaphore[] mutexes;
private int[] counters;
private Semaphore free;
private Semaphore weight;
private Semaphore kids;
public Tramboline(int maxWeight, int maxKids) {
mutexes = new Semaphore[] {
new Semaphore(1),
new Semaphore(1)
};
counters = new int[] {
0,
0
};
free = new Semaphore(1);
weight = new Semaphore(maxWeight);
kids = new Semaphore(maxKids);
}
public void getOn(Kid kid) {
int sex = kid.sex == Sex.MALE ? 1 : 0;
mutexes[sex].acquireUninterruptibly();
counters[sex]++;
if (counters[sex] == 1) {
free.acquireUninterruptibly();
}
mutexes[sex].release();
weight.acquireUninterruptibly(kid.weight);
kids.acquireUninterruptibly(1);
}
public void getOff(Kid kid) {
int sex = kid.sex == Sex.MALE ? 1 : 0;
mutexes[sex].acquireUninterruptibly();
counters[sex]--;
if (counters[sex] == 0) {
free.release();
}
mutexes[sex].release();
weight.release(kid.weight);
kids.release(1);;
}
}
private class Kid extends UtilThread {
private final Sex sex = getSex();
private final int weight = getWeight();
@Override
protected void step() {
resting();
tramboline.getOn(this);
try {
jumping();
} finally {
tramboline.getOff(this);
}
}
}
private enum Sex {
MALE, FEMALE;
}
}
与孩子和蹦床有关,这是某种读者和作家的问题。关键是男孩在跳,女孩必须等待,反之亦然。我要做的是,当男孩和女孩在一起等待时(蹦床空无一人),应优先考虑女孩,以便他们在男孩之前上车。你能帮我解决这个问题吗?谢谢。