Multithreading in Swing
Multithreading programs need to be careful about updating Swing components. The issue arises because Swing has its own event-dispatching thread. If your application is changing components in a different thread, bad things might happen: misshapen components or race conditions.
The fundamental rule is simple: if you need to update a Swing
component from your own thread, do it using invokeAndWait( )
or invokeLater( ). These are static methods in the
javax.swing.SwingUtilities
class.
-
public static voidinvokeLater(RunnabledoRun) Use this method to ask Swing to execute the
run( )method of the specifiedRunnable.-
public static voidinvokeAndWait(RunnabledoRun)throws InterruptedException,InvocationTargetException This method is just like
invokeLater( ), except that it waits until therun( )method has completed before returning.
A simple example is a download
progress
indicator. If your application downloads a lot of data from the
network, it should show a progress meter that indicates how much data
has been downloaded and how much remains. You shouldn’t update
this meter directly from the download thread; instead, you should
package updates in a Runnable
and use
invokeLater( ) or invokeAndWait( ).
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access