Multithreading 单车道桥梁问题的解决方案怎么不是无饥饿的?
我这里有一个单车道桥梁问题的解决方案。我想知道这个解决方案怎么不是无饥饿的 问题是,来自北方和南方的汽车到达一座单线桥。朝同一方向行驶的车辆可以同时通过桥梁,但朝相反方向行驶的车辆不能Multithreading 单车道桥梁问题的解决方案怎么不是无饥饿的?,multithreading,deadlock,semaphore,mutual-exclusion,starvation,Multithreading,Deadlock,Semaphore,Mutual Exclusion,Starvation,我这里有一个单车道桥梁问题的解决方案。我想知道这个解决方案怎么不是无饥饿的 问题是,来自北方和南方的汽车到达一座单线桥。朝同一方向行驶的车辆可以同时通过桥梁,但朝相反方向行驶的车辆不能 public class Bridge { static int N = 5 ; //# of cars coming in at the same time static int nN = 0; // # of northbound cars on bridge static int
public class Bridge {
static int N = 5 ; //# of cars coming in at the same time
static int nN = 0; // # of northbound cars on bridge
static int nS = 0; // # of southbound cars on bridge
static Semaphore e = new Semaphore(1); // entry to cs
static Semaphore n = new Semaphore(1); // delay for northbound cars
static Semaphore s = new Semaphore(1); // delay for southbound cars
}
public void Northbound() {
do {
P(Bridge.n);
Bridge.nN++;
if(Bridge.nN ==1) {
P(Bridge.e);
}
V(Bridge.n);
write(i,"northbound crossing");
P(Bridge.n);
Bridge.nN--;
if(Bridge.nN ==0) {
V(Bridge.e);
}
V(Bridge.n);
try{ sleep(1000) ; } catch (InterruptedException e) { } ;
} while (true) ;
}
public void Southbound() {
do {
P(Bridge.s);
Bridge.nS++;
if(Bridge.nS ==1) {
P(Bridge.e);
}
V(Bridge.s);
read(i,"northbound crossing");
P(Bridge.s);
Bridge.nS--;
if(Bridge.nS ==0) {
V(Bridge.e);
}
V(Bridge.s);
try{ sleep(1000) ; } catch (InterruptedException e) { } ;
} while (true) ;
}
void P(Semaphore s) {
try {
s.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//increment semaphore
void V(Semaphore s) {
s.release();
}