SafeAlley implementation
unknown
java
a year ago
1.3 kB
8
Indexable
public class SafeAlley extends Alley {
int up, down, t1, t2;
Semaphore alleySem, downIncrSem, upIncrSem;
protected SafeAlley() {
up = 0; down = 0;
alleySem = new Semaphore(1);
downIncrSem = new Semaphore(1);
upIncrSem = new Semaphore(1);
}
/* Block until car no. may enter alley */
public void enter(int no) throws InterruptedException {
if (no < 5) {
downIncrSem.P();
down++;
if (down == 1) alleySem.P();
downIncrSem.V();
} else {
upIncrSem.P();
up++;
if (up == 1) alleySem.P();
upIncrSem.V();
}
}
/* Register that car no. has left the alley */
public void leave(int no) {
try {
if (no < 5) {
downIncrSem.P();
down--;
if (down == 0) alleySem.V(); // enable up-going cars again
downIncrSem.V();
} else {
upIncrSem.P();
up--;
if (up == 0) alleySem.V(); // enable down-going cars again
upIncrSem.V();
}
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}Editor is loading...
Leave a Comment