2

我这里有一个单车道桥问题的解决方案。我想知道这个解决方案如何不是无饥饿的?

问题是来自北方和南方的汽车到达一个单车道的桥。同向车辆可以同时过桥,相反方向的车辆则不能。

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();
    }
4

0 回答 0