简体   繁体   中英

Java synchronization

I am bit stuck here, I have to have edit this code so that a train must wait in front of the tunnel lock for a train to come in the opposite direction to exit before it can enter the tunnel, i have to use java built in synchronisation condition

public synchronized void useTunnelLock(Train train)
{


    System.out.println(train + " " + train.getDirection());
    System.out.println(train + " exiting lock");
    try
    {
        // occupy tunnel lock for 5s
        Thread.sleep(5000);
    }
    catch (InterruptedException ex)
    {
        ex.printStackTrace();
    }

    // swap direction of tunnel lock
    direction = (direction == ASCENDING)? DESCENDING : ASCENDING;
}

看来使用信号量是合理的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM