在事件監聽器中直接執行耗時循環(如 while(true){ sleep(100); ... })會佔用 EDT,導致界面凍結、重繪停止、用戶操作無響應。
void startButton_actionPerformed(ActionEvent e) {
while (true) {
try { Thread.currentThread().sleep(100); } catch (InterruptedException er) {}
if (flagTrue) System.out.println("this is a test!");
}
}
後果: 點擊「Start」後,整個視窗無法移動、最小化、關閉,「Stop」按鈕點擊無效,因為 EDT 被死循環佔用,無法處理任何事件(含繪圖與鼠標點擊)。
void startButton_actionPerformed(ActionEvent e) {
if (thread != null) thread.stop(); // 注意:stop() 已棄用,現代應用用 interrupt/標誌位
thread = new MyThread();
thread.start();
}
private class MyThread extends Thread {
public void run() {
while (true) {
try { sleep(100); } catch (InterruptedException e) {}
System.out.println("this is a test!");
}
}
}
效果: 耗時循環在獨立線程運行,EDT 釋放處理繪圖、用戶交互,界面流暢響應,「Stop」按鈕可正常終止線程。
Thread、SwingWorker、ExecutorService 等。SwingUtilities.invokeLater() 或 invokeAndWait()。Thread.stop(): 採用 interrupt() + 標誌位優雅終止。「假如你能避免使用線程,最好這樣做。線程可能難於使用,並使得程序的 debug 更困難。一般來說,對於嚴格意義上的 GUI 工作,線程是不必要的。」