Do I need to switch to the Swing thread from the main application method?

In my method main(String[] args), I have nothing but a call SwingUtilities.invokeAndWaitto run the method main1in the Swing thread. I have always believed that I need this for thread safety. I was told that this is not necessary, because the first thread for any GUI code becomes a GUI thread. Or, to put it another way, you can only use Swing from a single thread, but it doesn't matter which one. But I cannot find a source for this, and I would like to be sure.

+5
source share
1 answer

What you were told is wrong. First, the method mainis called by the main thread. All GUI-related activities must be performed in a completely separate thread called Thread Dispatch Thread. The main thread does not turn into EDT.

A good example of what I say:

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));
            }
        });
    }
}
+7
source

All Articles