單線程程序中,四個無關任務(打印、文件操作、數據庫訪問、繪圖)串行等待,資源利用率極低。多線程讓任務並發執行,如同現實中「寫信時讓兒子去買郵票」。
public class TimePrinter extends Thread {
private int pauseTime;
private String name;
public TimePrinter(int pauseTime, String name) {
this.pauseTime = pauseTime;
this.name = name;
}
@Override
public void run() {
while (true) {
try {
System.out.println(name + ": " + new Date());
Thread.sleep(pauseTime);
} catch (Exception e) { e.printStackTrace(); }
}
}
public static void main(String[] args) {
new TimePrinter(1000, "Fast Guy").start();
new TimePrinter(3000, "Slow Guy").start();
// main 線程繼續運行...
}
}
缺點:Java 單繼承限制,若類已繼承 Applet 等則無法使用。
public class TimePrinter implements Runnable {
// 構造器、字段同前...
@Override public void run() { /* 同前 */ }
public static void main(String[] args) {
new Thread(new TimePrinter(1000, "Fast Guy")).start();
new Thread(new TimePrinter(3000, "Slow Guy")).start();
}
}
優勢:不強加類層次,同一 Runnable 實例可被多個 Thread 包裝,靈活構建線程池等模式。
new Thread(),未 start()run() 正常返回;不推薦 stop()(拋異常)、destroy()(強制終止不釋放鎖)MIN_PRIORITY) ~ 10 (MAX_PRIORITY),默認 5 (NORM_PRIORITY)getPriority()/setPriority() 動態調整public synchronized void accessVal(int newVal) { /* 訪問共享變量 */ }
this)Class 對象synchronized (syncObject) { // 只鎖住關鍵代碼段
// 訪問共享變量
}
syncObject 可為任意對象,通常用 this 或共享數據對象run())整體同步導致並發度崩潰Runnable + 線程池 (ExecutorService) 管理線程生命周期ThreadLocal、不可變對象、並發集合 (java.util.concurrent)