Topics in Java Swing, An Overview of Three Approaches in an Application

I use the code below in a desktop application and I don’t have much experience with threads, because I am a random web programmer and dealing with swings is not my sweet ...

I want to know if there is a better approach to managing my 3 tasks, and I need to run them in parallel for the thread in my application.

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!

+4
source share
2 answers

What are you trying to do? Does your thread work in the Swing GUI or is it independent of the GUI?

You should use invokeLater() if the thread is doing something with the Swing user interface, because this can only be done from the event dispatch thread . Swing single-threaded. (Your task 1 and 2)

If you do something completely in the background, for example. by writing a large XML file that can be made in the background thread . (Your task 3) But you can still communicate with the Swing GUI using invokeLater() .

Another alternative is that you want to run a thread regularly, for example. every 5th minute you can use TimerTask . Or, if it is not dependent on the Swing GUI java.util.TimerTask .

Concurrency in Swing might be worth reading:

The Swing programmer has the following types of threads:

  • Initial threads, threads that execute the source code of the application.
  • an event dispatch thread where all event processing code is executed. Most of the code that interacts with the Swing framework should also run in this thread.
  • Workflows, also known as background threads, where time-consuming background tasks are performed.
+6
source

# 1 and # 2 match. You should use the number # 1, since the known part of the API.

If you use # 1 or # 3, it depends on the following:

Is this making changes to the user interface or its swap model? If yes, use # 1.

This is a long-term task: If yes, use # 3.

If this is a long-term task that will ultimately change the user interface or its support model, run the long-term task in a separate thread, and then call incokeLater to update the user interface.

Also, instead of creating a new thread, use the ExecutorService each time so you can reuse the threads.

This can be a little more complicated, for example, if you are currently in the event stream (i.e. in ActionListener.actionPerformed() , then you do not need (as it should not) to invokeLater, but its essence is there.

+7
source

All Articles