in the book that i'm reading, every example of GUI with multithreading has something like that:
public static void main(String[] args) throws Exception
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new SomeKindOfFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
(i mean EventQueue). but isn't the code automatically executed in the main (EDT) thread?
invokeLater. public static void invokeLater(Runnable runnable) Causes runnable to have its run method called in the dispatch thread of the system EventQueue . This will happen after all pending events are processed.
An invokeLater() method is a static method of the SwingUtilities class and it can be used to perform a task asynchronously in the AWT Event dispatcher thread. The SwingUtilities. invokeLater() method works like SwingUtilities. invokeAndWait() except that it puts the request on the event queue and returns immediately.
Difference on InvokeLater vs InvokeAndWait in Swing 1) InvokeLater is used to perform a task asynchronously in AWT Event dispatcher thread while InvokeAndWait is used to perform task synchronously. 2) InvokeLater is a non-blocking call while InvokeAndWait will block until the task is completed.
SwingUtilities class has two useful function to help with GUI rendering task: 1) invokeLater(Runnable):Causes doRun. run() to be executed asynchronously on the AWT event dispatching thread(EDT). This will happen after all pending AWT events have been processed, as is described above.
The main thread isn't the same as the EDT. If you add System.out.println(Thread.currentThread().getName()
you'll see it print out main
within main()
and AWT-EventQueue-0
when within the run()
method of the Runnable
.
Here is a discussion of the history of the single threaded rule in Swing that might help make things clearer.
Desktop GUI applications usually work in this way. There is one thread for gui and one or several threads for rest of application. Using EventQueue
you specify what GUI thread should do from other threads.
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