Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("每秒執行: " + new Date());
}
}, 0, 1000); // 立即開始,每 1000ms
// 停止
timer.cancel();
適用:簡單週期性任務、無需複雜協調。
Timer swingTimer = new Timer(500, e -> {
label.setText("計數: " + count++); // 在 EDT 執行,安全更新 UI
});
swingTimer.start();
關鍵:事件處理執行緒 (EDT) 執行,符合 Swing 單執行緒規則。
class MyThread extends Thread {
public void run() {
// 任務邏輯
}
}
new MyThread().start();
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()、捕獲 InterruptedExceptionExecutorService| 誤區 | 正確做法 |
|---|---|
| 直接呼叫 run() | 必須呼叫 start() 啟動新執行緒 |
| 共享可變狀態無同步 | 用 Atomic、ThreadLocal、不可變物件 |
| 在同步區塊睡眠/阻塞 | 縮小鎖範圍、避免長時間持有鎖 |
| 忽略 InterruptedException | 重設中斷旗標或拋出 |