Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads in Java Swing, overview of three approaches in an application

I'm using the code bellow in a desktop swing application, and I don't have much expertise with threads, because I'm a casual web programmer and deal with swing isn't my candy...

I want to know if have better approach to control my 3 tasks and I need running them in parallel one for thread in my app.

    SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            task 1                
         }
    });


    Runnable r;
    r = new Runnable() {

        public void run() {
            task 2                  
        }
    };
    EventQueue.invokeLater(r);


    Thread worker = new Thread() {

        public void run() {
            task 3                 
        }
    };

    worker.start();

Thanks!

like image 291
Bera Avatar asked Dec 12 '22 12:12

Bera


1 Answers

#1 and #2 are the same. You should use number #1 since that's the well-known part of the API.

Whether you use #1 or #3 depends on the following:

Is it making changes to the user interface or its backing models? If yes, use #1.

Is it a long-running task: If yes, use #3.

If it is a long-running task that will eventually modify the user interface or its backing model, perform the long running task in a separate thread, and then call incokeLater to update the user interface.

Furthermore, instead of creating a new thread every time, use an ExecutorService so you can reuse threads.

It can get a little bit more complicated, for example, if you're currently in the event thread (ie: in an ActionListener.actionPerformed(), then you don't need to (as in shouldn't) call invokeLater, but the gist of it is up there.

like image 61
Reverend Gonzo Avatar answered Dec 21 '22 22:12

Reverend Gonzo