简体   繁体   中英

Multi-threading with Swing

I am trying to write a multi-thread program with Swing. Essentially how the program works is that when it runs it will have a robot(represented by a circle in screenshot) that is wondering around in a field. This robot should be controlled by a thread of it's own. The program has a button "Launch Robot" that will create another robot on the field(upto a max of say 10). Right now I have the basics of the program, but it all runs under one thread. I can launch as many robots as I want but they all run under a single thread. But I want that whenever I click "launch Robot" an independent thread be created and control that robot. This is how the program looks right now: 在此处输入图片说明

The UML diagram for the program is as following: 在此处输入图片说明

Since its a bit long I won't post the whole program. But the method that starts and updates the robots(currently controlling only one robot on the field) is as follows:

    public void gameStart(){
    Thread gameThread = new Thread(){
        public void run(){
            while(true){
                //execute one time step for the game
                gameUpdate();

                //refresh screen
                repaint();

                //give other threads time
                try{
                    Thread.sleep(1000/UPDATE_RATE);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    };

    gameThread.start();
}

My question is how can I achieve multi-threading for such a scenario? I know the basics of SwingWorker , but since I haven't done any multi-threading, I have no idea on how to make several threads work and be updated by one thread(update position of robots that are controlled by threads).

EDIT: Just to make my point, this is a project that I am working on. It's not about if multi-threading makes sense in this scenario or not.

Create a RobotModel that contains a Collection<Robot> and defines their interaction. Iterate the model in the doInBackground() implementation of a SwingWorker . Invoke publish() as meaningful events arise, and process() updates to the RobotWorld view by querying the model. As discussed here , there should be no drawing in the model and no interaction logic in the view. A single worker should suffice for a moderately complex model, but you can synchronize multiple workers as shown here .

A good option to achieve this is to use ScheduledThreadPoolExecutor .
Instantiate the thread pool via:

ScheduledThreadPoolExecutor threadsPool = new ScheduledThreadPoolExecutor(size);

To create a new Robot Thread, use:

    threadsPool.submit(new Runnable() {
        @Override
        public void run() {
            launchRobot();
        }
    });

This way, each invocation will instantiate a new Thread.
You can set the limit of the total number of allowed Thread via the "size" argument.
You can also pass a result after each thread completes using:

public <T> Future<T> submit(Runnable task, T result) 

If you want less detail, you could let Java do the work for you with the following convenience API:
Executors.newCachedThreadPool() (unbounded thread pool, with automatic thread reclamation) or:
Executors.newFixedThreadPool(int) (fixed size thread pool)

Remember us, Executor. Remember what was done here today. And may Adun watch over you

This robot should be controlled by a thread of it's own.

Why?

IMO, the most important way to describe any thread is to say what it waits for. In an internet server, an accept thread waits for incoming connections from new clients, and a client thread waits for additional commands from a single client. In a program that performs massive parallel computations, a worker thread waits for tasks to be performed. In a GUI program, the event dispatch thread waits for keyboard and mouse events. Etc., etc.

What will your robot thread wait for?

If it waits for time to pass (ie, if it calls Thread.sleep()), then your GUI framework probably already has a timer thread that does that, and you might want to consider using it. (In Swing, you would use the javax.swing.Timer class to submit new timed tasks.)

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