简体   繁体   中英

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. To stop it, you can use break under right conditions. 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. 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() . A waiting thread can be 'woken up' if another thread calls notify on waiters monitor. Get some more info about wait() and notify to get a better understanding of it. Afterwards implementation should not be a problem then.

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