我有点卡在这里,我必须编辑此代码,以便火车必须在隧道锁前等待火车从相反方向驶出才能进入隧道,我必须使用java内置同步条件
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;
}
最佳答案
这看起来使用 semaphore 是合理的。 .
关于Java同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5708508/