简体   繁体   English

如何用同步,等待和通知的Java监视器替换Java Semaphore的获取和发布(全部)

[英]How to replace Java Semaphore's acquire and release with Java monitors synchronized, wait and notify(All)

My code works with semaphores, but I want to make this work with Java monitors: wait, notify, notifyAll and synchronized instead of acquire and release. 我的代码适用于信号量,但我想使它适用于Java监视器:等待,通知,notifyAll和已同步,而不是获取和释放。 Can anyone tell me how I can do this? 谁能告诉我该怎么做?

public class Track {

    private final Semaphore mutex = new Semaphore(1,true);
    private final Semaphore use = new Semaphore(1,true);

    public Track(){}

    public void gebruikWissel(String v) throws InterruptedException
    {
        mutex.acquire();
        System.out.format("Trein %s maakt gebruik van de wissel", v);
        mutex.release();
    }

    public void useTrack() throws InterruptedException
    {
        use.acquire();
    }

    public void stopUseTrack()
    {
        use.release();
    }
}

you can do it using synchronized and a simple internal counter, eg: 您可以使用同步的和简单的内部计数器来完成此操作,例如:

private int counter;

public synchronized void useTrack() throws InterruptedException
{
    while(counter == 1) {
      wait();
    }
    counter++;
}

public synchronized void stopUseTrack()
{
    counter--;
    notifyAll();
}

UPDATE: didn't realize this was homework. 更新:没有意识到这是家庭作业。 well, i hope i get a good grade! 好吧,我希望我能获得好成绩!

I don't think you can the way your class is structured. 我认为您无法以这种方式构造您的班级。 You can't even write a useTrack() or 'stopUseTrack()' method that use synchronization, for example. 例如,您甚至无法编写使用同步的useTrack()或'stopUseTrack()'方法。

It is more common for people to go from synchronization to semaphores. 人们同步信号灯更为常见。 Why do you think you want to go in the opposite direction. 为什么您认为您想朝相反的方向前进。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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