简体   繁体   English

Java并发唤醒线程

[英]Java Concurrency wake up thread

I have an assignment in concurrent programming, and I am wondering how I can go about something. 我在并发编程中有一个工作,我想知道如何处理某些事情。 I have to have an elevator simulator, where people call elevators, elevators will collect them and bring them to their destination floor. 我必须有一个电梯模拟器,人们可以在这里呼叫电梯,电梯将把它们收集起来并带到目的地楼层。 When an elevator isn't doing anything it sleeps and the Person will have a method to wake the elevator(by pressing the button). 当电梯不执行任何操作时,它将进入睡眠状态,并且此人将有一种方法(通过按按钮)来唤醒电梯。

Eventually the program will have to run forever, with elevators being created at the start of it, and people being created at random times, constantly calling the elevator. 最终,该程序将永远运行,在其开始处创建电梯,并在随机时间创建人员,不断调用电梯。 I'm wondering, how can I make it so the program runs forever, until I stop it, where the elevator waits for a Person to wake it. 我想知道如何使它永久运行,直到我停止它,然后电梯在这里等待一个人将其唤醒。

In my main class I have this right now: 在我的主班上,我现在有这个:

    new Thread(elevators[0]).start();

    panels[3].pressButton().getButtonPanel().pressButton(5);
    panels[1].pressButton().getButtonPanel().pressButton(0);
    panels[2].pressButton().getButtonPanel().pressButton(4);

I also have an array of People, but I want that to be something generated constantly and randomly. 我也有一系列的人,但是我希望它是不断不断地随机产生的东西。 So in the Person class they will wake the elevator, but how can I make the elevator sleep forever here? 因此,在“人”课程中,他们将唤醒电梯,但是我如何才能使电梯在这里永远睡眠呢? Thanks for any help 谢谢你的帮助

To run forever, just put all of your code inside a while(true) loop. 要永久运行,只需将所有代码放入while(true)循环中。 To stop it, you can use break under right conditions. 要停止它,可以在适当的条件下使用break。 Alternatively (and to have a possibly cleaner code) use a while(condition) loop, where your condition gets changed from true to false by some method you can call. 另外(为了使代码更清晰),可以使用while(condition)循环,在这种情况下,您可以通过调用某些方法将条件从true更改为false。 For example have all this in your class: 例如,在您的课堂上拥有所有这些:

boolean shouldBeRunning = true;

(...)

while(shouldBeRunning){
    //all the logic here
}

(...)

public void stop(){
    this.shouldBeRunning = false;
}

To have elewator waiting until somebody calls it, use method wait() . 要让elevator等到有人调用它,请使用方法wait() A waiting thread can be 'woken up' if another thread calls notify on waiters monitor. 如果另一个线程调用了在waiters监视器上的notify ,则可以“唤醒”正在等待的线程。 Get some more info about wait() and notify to get a better understanding of it. 获取有关wait()更多信息,并进行notify以更好地了解它。 Afterwards implementation should not be a problem then. 然后,实施应该不是问题。

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

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