Home >Java >javaTutorial >Why Does Thread.sleep() Freeze My Swing UI?
Impact of Java's Thread.sleep() on Swing UI
In Java, utilizing Thread.sleep() in a Swing-based application can have an unintended consequence of pausing the entire user interface, rendering it unresponsive.
Problem Description:
Consider the following code snippet:
<code class="java">// Code to create a simple Swing-based application if (option == JFileChooser.APPROVE_OPTION) { selectedDirectory = chooser.getSelectedFiles(); try { while (true) { runCheck(selectedDirectory); Thread.sleep(1000 * 5);//1000 is 1 second } } catch (InterruptedException e1) { Thread.currentThread().interrupt(); e1.printStackTrace(); } } </code>
This application uses Thread.sleep() to pause for 5 seconds before performing a check. However, during this sleep period, the user interface becomes unresponsive and greyed out.
Reason for UI Inactivity:
Thread.sleep() pauses the thread that calls it, in this case, the Event Dispatch Thread (EDT). The EDT is responsible for handling all GUI events and rendering the user interface. Therefore, when the EDT goes to sleep, the UI ceases to respond to input and update its display.
Alternative Approach:
To avoid freezing the UI, a more appropriate solution is to use a javax.swing.Timer. A timer can schedule tasks to be executed off the EDT at specified intervals:
<code class="java">Timer t = new Timer(1000 * 5, new ActionListener() { public void actionPerformed(ActionEvent e) { // do your recurring task } });</code>
In this case, the task of performing the check is scheduled to run every 5 seconds off the EDT, allowing the UI to remain responsive while the check is running.
The above is the detailed content of Why Does Thread.sleep() Freeze My Swing UI?. For more information, please follow other related articles on the PHP Chinese website!