本文聚焦 Thread 兩個核心協作方法:setDaemon() 與 join(),它們決定了線程的生命週期與執行順序。
setDaemon(true) 標記為守護線程(默認 false)。public class DaemonSample {
public static void main(String[] args) throws Exception {
DaemonThread t = new DaemonThread();
t.setDaemon(true); // 標記為守護線程
t.start();
Thread.sleep(2000);
System.out.println("main thread exit."); // 主線程結束,JVM 退出
}
}
class DaemonThread extends Thread {
public void run() {
for (int i=0; i<10; i++) {
Thread.sleep(1000);
System.out.println("i=" + i); // 只能跑 2 次就被強制終止
}
}
}
註釋 setDaemon(true) 後,主線程結束但子線程會繼續跑完 10 秒。
wait(0))。public class JoinSample {
public static void main(String[] args) throws Exception {
Thread t = new Thread(new SubThread());
t.start();
t.join(); // main 阻塞,等待 t 結束
System.out.println("The end of main thread...");
}
}
class SubThread implements Runnable {
public void run() {
Thread.sleep(2000);
System.out.println("The end of sub thread..."); // 先打印這行
}
}
註釋 t.join() 後,main 線程不再等待,先結束。
從單核到多核(雙核、4核、48核…),硬件推動了並發編程從「可選」變為「必修」。掌握線程基礎協作,是利用多核優勢的第一步。