Reputation:
As far as I know, there are 3 threads in a Swing GUI application:
main()
methodGenerally, the main method just makes a call to SwingUtilities#invokeLater(Runnable)
in order to initialize a window and so on, thus the GUI initialization is made on the EDT... BTW, as far as I know (again), everything that touches the GUI must be executed on the EDT...
Questions: What is the main thread used / usable for? Does it just die after the call to invokeLater()
? Does it consume resources? Can I (and is it a good practice to) use it to perform... I don't know... Network stuff?
Upvotes: 4
Views: 414
Reputation: 27210
The main thread in a Java program dies when control reaches the end of main()
.
In the program architecture that you describe, the main thread already has created the EDT and maybe other threads by that point, and those other threads keep the JVM alive.
Every thread in Java is either a daemon thread, or a non-daemon thread. The latter is the default case for a new Thread
. You have to call t.setDaemon(true)
if you want a daemon.
A JVM will keep running as long as there is at least one non-daemon thread still alive.
What is the main thread used / usable for?
It is usable for any purpose that you would use any other thread for. It executes whatever code you write for it to execute.
Upvotes: 1
Reputation: 2509
A Swing programmer deals, actually, with 3 kinds of threads:
The inital thread creates the Runnable to run swings tasks and schedule it in the EDT. After that, the program is primarly driven by the GUI, and the application code survives and can continue to execute other tasks (Network staff as you noticed) and consumes resources as much as it needs.
Any Swing component method must be invoqued by the EDT (but some of them) because they swing method are not "thread-safe". So,
SwingUtilities#invokeLater(Runnable)
just queues the runnable in the EDT task list and wait for its turn to run.
The doc here is quite helpful.
Upvotes: 2