I know what \"thread\" means and if I understand the event dispatching thread (EDT) as \"just a thread\", it explains a lot but, apparently, it does not explain everything.
I always thought that we have one "task" per thread. So, in every thread we execute a predefined sequence of commands. But it seems to me that in the event dispatching thread we can have sever task. Well, they are not executed simultaneously (thread switches between different task but there are still several task in one thread). Is it right? For example there is one thread in the EDT which display the main window, and then additionally to that we sent to the EDT another task which should update one of the window components and EDT will execute this new task whenever it is ready. Is EDT differ from other threads in this way?
No, the EDT is not fundamentally different from other threads. And "task" is not a good word to use, because it could be confused with OS-level processes (which are also often called task). Better use Runnable
, the interface used to give code to the EDT to execute via invokeLater()
.
The EDT is basically connected to a queue of things it has to do. When the user clicks a button on the GUI, a Runnable
that notifies all listeners attached to the button goes into the queue. When a window is resized, a Runnable
doing revalidate&repaint goes into the queue. And when you use invokeLater()
, your Runnable
goes into the queue.
The EDT simply runs an endless loop that says "take a Runnable
from the queue (and if it's empty sleep until you're notified that it's not) and execute it.
Thus, it executes all those little Runnable
pieces of code one after another, so that each of them basically has the GUI all to itself while it runs, and doesn't have to worry about synchronizing anything. When you manipulate the GUI from another thread, this assumption is broken, and you can end up with the GUI in a corrupted state.