Event Dispatching Thread - Executing Code in The EDT

Executing Code in The EDT

Other application threads can have code executed in the event dispatching thread by defining the code in a Runnable object and pass it to the SwingUtilities helper class or to the EventQueue. Two methods of these classes allow:

  • synchronous code execution (SwingUtilities.invokeAndWait(Runnable) or EventQueue.invokeAndWait(Runnable))
  • and asynchronous code execution (SwingUtilities.invokeLater(Runnable) or EventQueue.invokeLater(Runnable))

from the EDT.

The method invokeAndWait should never be called from the event dispatching thread—it will throw an exception. The method SwingUtilities.isEventDispatchThread or EventQueue.isDispatchThread can be called to determine if the current thread is the event dispatching thread.

Another solution for executing code in the EDT is using the worker design pattern. The SwingWorker class, developed by Sun Microsystems, is an implementation of the worker design pattern, and as of Java 6 is part of standard Swing distribution. The open source project Foxtrot provides another synchronous execution solution similar to SwingWorker.

Read more about this topic:  Event Dispatching Thread

Famous quotes containing the words executing and/or code:

    Executives are like joggers. If you stop a jogger, he goes on running on the spot. If you drag an executive away from his business, he goes on running on the spot, pawing the ground, talking business. He never stops hurtling onwards, making decisions and executing them.
    Jean Baudrillard (b. 1929)

    Many people will say to working mothers, in effect, “I don’t think you can have it all.” The phrase for “have it all” is code for “have your cake and eat it too.” What these people really mean is that achievement in the workplace has always come at a price—usually a significant personal price; conversely, women who stayed home with their children were seen as having sacrificed a great deal of their own ambition for their families.
    Anne C. Weisberg (20th century)