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.
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));
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With