简体   繁体   中英

Running Threads and Controlling Them

I need help figuring out how to code this problem I am running into.

I'm creating an elevator simulator. I want to run each Elevator object in separate individual threads. I want to control them with my ElevatorController object. I am imagining the Elevator threads sitting in IDLE and then switching to UP or DOWN when the ElevatorController tells it to.

I have created the Elevators and put them into an ArrayList that is stored in the Building object.

What do I do next? My objective is to make elevator1 go to Floor 11. While elevator1 is moving I need to tell elevator2 to go to Floor 14. As elevator2 is moving to Floor 14, I need to tell it to go to Floor 13 first.

I'm unsure how I am supposed to create these threads and still have a reference to the elevator objects in these threads, so I can tell them the new destination.

I'm new to multithreading.

Define each thread as a field in your building so you can access it later. I would do something like:

public class ElevatorThread extends Thread {
    public void run() {
        while(!this.interrupted()) {
            synchronized(this) {
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    return;
                }
            }
            elevatorThreadRunnable.run();
        }
    }
    Runnable elevatorThreadRunnable;
    public void setRunnable(Runnable runnable) {
        elevatorThreadRunnable = runnable;
        synchronized (this) {
            this.notify();
        }
    }
}

If we define the ElevatorThread s as an array it gets even easier. We can simply:

building.elevatorThreads[0].setRunnable(new Runnable() {
    public void run() {
        ...
    }
});

Where:

//I belong in the Building constructor!
Thread[] elevatorThreads = {
    new ElevatorThread(),
    new ElevatorThread(),
    new ElevatorThread()
    //number of elevators in building
    /*
        this could be simplified to a method that takes the number of threads as an int
        and returns an inflated array, but that is outside the context of this answer
    */
};

If we do this, our Runnable is ran in the elevator thread of your choosing. The thread will also idle like you requested, until a new Runnable is set.

To kill a thread, we call ElevatorThread.interrupt(); , this will cause the thread to stop wait() ing if it is, and then break out of our execution loop; killing the thread.

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