Using sleep() for a Single Thread
In Java, wait() and sleep() are employed to handle thread synchronization. However, when trying to utilize sleep() on a single thread while running others, an issue may arise.
Problem:
When calling sleep() on one thread, both threads appear to pause execution for the specified duration. Why is this behavior occurring?
Answer:
When working with Swing GUIs, a unique thread distinct from the main and other threads is responsible for its creation. This thread is known as the Event Dispatch Thread (EDT). If sleep() is invoked on EDT, it halts execution until the call is completed.
Since GUI event processing occurs on EDT, any sleep operation on this thread pauses event handling, causing the UI to appear frozen until sleep() concludes.
Solution:
Avoid using Thread.sleep() on EDT or threads where sleep() would result in unintended execution blocking. Alternatively, consider the following options:
Note:
For Java 1.6 or later, Swing Timer and Swing Worker are preferred options for delaying actions on EDT. For earlier Java versions, TimerTask or Thread can be used in conjunction with SwingUtilities/EventQueue#invokeXX block to ensure UI responsiveness.
The above is the detailed content of Why Does Calling `sleep()` on the Event Dispatch Thread Freeze the GUI?. For more information, please follow other related articles on the PHP Chinese website!