Should Swing GUI application be controlled from Event Dispatcher or main thread?

a 夏天 提交于 2019-12-03 21:35:07

ALL interactions with any UI/Swing component MUST be done for within the context of the EDT

When starting an application, you should ensure that you are executing within the EDT BEFORE you try and create/interact with any Swing component.

Simply put, you should use something like...

EventQueue.invokeLater(new Runnable() {
    public void run() {
        // Now in the event dispatching thread
    }
});

If you need to run long running task or perform any blocking task, you should execute it in a separate thread. SwingWorker is a good choice in most cases as it provides some simple mechanisms for re-syncing code to the event dispatching thread.

Take a read through

So, the short answer is, yes, all Swing based code should be accessed/modified/interacted with from the context of the EDT

So if i am not mistaken, in every Swing based GUI application there are at least two threads

Yes. One is main thread and other is EDT(Event Dispatch Thread).

This makes every GUI application multithreaded.

Yes. But in that case , the other thread is not interacting with the GUI component.

Swing doesn't support multithreading therefore all GUI components should be created and modified only in Event Dispatcher Thread otherwise Thread Interference and Memory Inconsistency Errors may arise.

Yes , Absolutely true. This means that at a time only one Thread should interact with the given GUI component.
A Swing programmer deals with the following kinds of threads:

  • Initial threads, the threads that execute initial application code.
  • The event dispatch thread, where all event-handling code is executed. Most code that interacts with the Swing framework must also execute on this thread.
  • Worker threads, also known as background threads, where time-consuming background tasks are executed.

The programmer does not need to provide code that explicitly creates these threads: they are provided by the runtime or the Swing framework. The programmer's job is to utilize these threads to create a responsive, maintainable Swing program.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!