首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 程式開發中執行緒應用實戰:Timer、SwingWorker、Thread/Runnable 完整指南

     編輯:Java 相關知識

四大執行緒建立方式

1. java.util.Timer (定時任務)

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
    public void run() {
        System.out.println("每秒執行: " + new Date());
    }
}, 0, 1000); // 立即開始,每 1000ms

// 停止
timer.cancel();

適用:簡單週期性任務、無需複雜協調。

2. javax.swing.Timer (Swing 安全)

Timer swingTimer = new Timer(500, e -> {
    label.setText("計數: " + count++); // 在 EDT 執行,安全更新 UI
});
swingTimer.start();

關鍵:事件處理執行緒 (EDT) 執行,符合 Swing 單執行緒規則。

3. 繼承 Thread 類別

class MyThread extends Thread {
    public void run() {
        // 任務邏輯
    }
}
new MyThread().start();

4. 實作 Runnable 介面 (推薦)

Runnable task = () -> {
    // 任務邏輯
};
new Thread(task).start();
// 或提交執行緒池
executor.submit(task);

優勢:職責分離、可重用、支援 Lambda、易於測試。

實戰範例:非阻塞下載 + 進度顯示

public class DownloadDemo {
    public static void main(String[] args) {
        String url = "https://example.com/large.zip";
        
        // 下載執行緒
        Thread downloader = new Thread(() -> {
            try (InputStream in = new URL(url).openStream()) {
                byte[] buf = new byte[8192];
                int len, total = 0;
                while ((len = in.read(buf)) != -1) {
                    total += len;
                    System.out.println("已下載: " + total + " bytes");
                }
            } catch (IOException e) { e.printStackTrace(); }
        });
        
        // 進度顯示執行緒
        Thread reporter = new Thread(() -> {
            while (downloader.isAlive()) {
                System.out.println("下載中...");
                try { Thread.sleep(2000); } catch (InterruptedException ignored) {}
            }
            System.out.println("下載完成");
        });
        
        downloader.start();
        reporter.start();
        
        // 等待結束
        try { downloader.join(); reporter.join(); } 
        catch (InterruptedException e) { Thread.currentThread().interrupt(); }
    }
}

關鍵最佳實務

  • 守護執行緒:setDaemon(true) 避免阻塞 JVM 退出
  • 中斷處理:檢查 Thread.interrupted()、捕獲 InterruptedException
  • 資源清理:try-with-resources、finally 區塊
  • 執行緒池:生產環境避免手工建立 Thread,使用 ExecutorService
  • Swing/JavaFX:UI 更新必須在事件執行緒 (EDT/JavaFX Application Thread)

常見誤區

誤區正確做法
直接呼叫 run()必須呼叫 start() 啟動新執行緒
共享可變狀態無同步用 Atomic、ThreadLocal、不可變物件
在同步區塊睡眠/阻塞縮小鎖範圍、避免長時間持有鎖
忽略 InterruptedException重設中斷旗標或拋出
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved