Java 平台天生多線程:主程序運行時,垃圾回收、事件處理等在後台線程執行。開發者可利用多線程處理並發任務,主要工具類包括:
java.util.Timer:通用定時任務javax.swing.Timer:Swing 專用,事件分發線程執行Thread 類與 Runnable 接口:完全控制適用於固定頻率執行的輕量任務。任務定義在 TimerTask.run() 中:
import java.util.*;
public class Hi {
public static void main(String[] args) throws Exception {
TimerTask task = new TimerTask() {
public void run() { System.out.println("Hi"); }
};
Timer timer = new Timer();
timer.schedule(task, 0, 500); // 0 延遲,每 500ms 執行
System.out.println("Press ENTER to stop");
System.in.read(new byte[10]);
timer.cancel(); // 取消定時器,程序退出
}
}
關鍵點:JRE 只要有非守護線程運行就不退出;Timer 默認創建非守護線程,cancel() 後無其他線程則程序結束。
Swing 非線程安全,所有組件操作必須在事件分發線程(EDT)執行。javax.swing.Timer 的監聽器自動在 EDT 運行:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Count {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("", JLabel.CENTER);
label.setFont(new Font("Serif", Font.PLAIN, 36));
frame.getContentPane().add(label, BorderLayout.CENTER);
ActionListener listener = new ActionListener() {
int count = 0;
public void actionPerformed(ActionEvent e) {
label.setText(String.valueOf(++count)); // 安全更新 UI
}
};
new Timer(500, listener).start(); // 每 500ms 觸發
frame.setSize(300, 100);
frame.setVisible(true);
}
}

兩種方式:繼承 Thread 重寫 run(),或實現 Runnable 傳給 Thread 構造器。後者更靈活,避免繼承限制。
import java.io.*;
import java.net.*;
public class Both {
public static void main(String[] args) {
final String url = args[0];
final String msg = args[1];
// 方式一:匿名 Thread 子類 - 下載網頁統計字符數
Thread t1 = new Thread() {
public void run() {
try {
URL u = new URL(url);
BufferedReader r = new BufferedReader(
new InputStreamReader(u.openConnection().getInputStream()));
int cnt = 0; while (r.read() != -1) cnt++;
System.out.println("Size is: " + cnt);
r.close();
} catch (Exception e) { e.printStackTrace(); }
}
};
t1.start();
// 方式二:Runnable - 定期打印消息
Runnable r = () -> {
while (true) {
System.out.println(msg);
try { Thread.sleep(500); } catch (InterruptedException ignored) {}
}
};
new Thread(r).start();
// 主線程等待用戶輸入退出
try {
System.out.println("Press ENTER to stop");
System.in.read(new byte[10]);
} catch (IOException ignored) {}
System.exit(0);
}
}
java.util.Timerjavax.swing.TimerThread + RunnableExecutorService、ScheduledExecutorService、CompletableFuture。