J.17. Multithreading with GUI

Swing applications present a unique set of challenges for multithreaded programming. All Swing applications have an event dispatch thread to handle interactions with the GUI components. Typical interactions include updating GUI components or processing user actions such as mouse clicks. All tasks that require interaction with an application’s GUI are placed in an event queue and are executed sequentially by the event dispatch thread.

Swing GUI components are not thread safe—they cannot be manipulated by multiple threads without the risk of incorrect results. Thread safety in GUI applications is achieved not by synchronizing thread actions, but by ensuring that Swing components are accessed from the event dispatch thread—a technique called thread confinement.

Usually it’s sufficient to perform simple tasks on the event dispatch thread in sequence with GUI component manipulations. If a lengthy task is performed in the event dispatch thread, it cannot attend to other tasks in the event queue while it’s tied up in that task. This causes the GUI to become unresponsive. Long-running tasks should be handled in separate threads, freeing the event dispatch thread to continue managing other GUI interactions. Of course, to update the GUI based on the tasks’s results, you must use the event dispatch thread, rather than from the worker thread that performed the computation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset