Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to switch to the Swing thread from an application's main method?

In my main(String[] args) method I have naught but a call to SwingUtilities.invokeAndWait to run a main1 method on the Swing thread. I always assumed I needed this for thread safety. I've been told that it isn't necessary because the first thread to do any GUI code becomes the GUI thread. Or to put it another way, you can only use Swing from one thread, but it doesn't matter which one. But I can't find a source for this and I'd like to be certain.

like image 575
Boann Avatar asked Jun 12 '12 22:06

Boann


1 Answers

What you have been told is false. The main method will initially be called by the main thread. All GUI related activity must be performed on a completely separate thread called the Event Dispatch Thread. The main thread does not become the EDT.

A nice example to see what I'm talking about:

public class ThreadTest {
    public static void main(String[] args) {
        final Thread main = Thread.currentThread();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Thread edt = Thread.currentThread();

                System.out.println(main);
                System.out.println(edt);
                System.out.println(main.equals(edt));
            }
        });
    }
}
like image 196
Jeffrey Avatar answered Oct 21 '22 19:10

Jeffrey