在 Java 中,創建線程主要有三種方式,每種方式各有特點和適用場景。以下是詳細說明和代碼示例:
1. 繼承 Thread
類
原理:自定義類繼承 Thread
并重寫 run()
方法,通過調用 start()
啟動新線程。
特點:簡單直接,但 Java 是單繼承,無法再繼承其他類。
class MyThread extends Thread {@Overridepublic void run() {System.out.println("線程運行: " + Thread.currentThread().getName());}
}public class Main {public static void main(String[] args) {MyThread thread = new MyThread();thread.start(); // 啟動新線程(非阻塞)System.out.println("主線程繼續執行");}
}
2. 實現 Runnable
接口
原理:實現 Runnable
接口的 run()
方法,將實例傳遞給 Thread
對象。
特點:更靈活(可繼承其他類),推薦使用(避免單繼承限制)。
class MyRunnable implements Runnable {@Overridepublic void run() {System.out.println("線程運行: " + Thread.currentThread().getName());}
}public class Main {public static void main(String[] args) {Thread thread = new Thread(new MyRunnable());thread.start(); // 啟動新線程// 或使用 Lambda 簡化(Java 8+)new Thread(() -> System.out.println("Lambda 線程")).start();}
}
3. 實現 Callable
接口 + FutureTask
原理:實現 Callable
的 call()
方法(可返回結果和拋出異常),配合 FutureTask
獲取返回值。
特點:支持返回值、異常處理,適用于需要結果的多線程場景。
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;class MyCallable implements Callable<String> {@Overridepublic String call() throws Exception {return "線程返回值: " + Thread.currentThread().getName();}
}public class Main {public static void main(String[] args) throws Exception {FutureTask<String> futureTask = new FutureTask<>(new MyCallable());Thread thread = new Thread(futureTask);thread.start();String result = futureTask.get(); // 阻塞獲取返回值System.out.println(result);}
}
關鍵注意事項
-
啟動線程必須調用
start()
而非run()
start()
:JVM 創建新線程并異步執行run()
。run()
:僅在當前線程同步執行方法(不會啟動新線程)。
-
線程生命周期
新建(New)→ 就緒(Runnable)→ 運行(Running)→ 阻塞(Blocked)→ 終止(Terminated)。 -
推薦使用
Runnable
或Callable
更靈活,符合面向接口編程原則,適合線程池管理。 -
線程池(高級用法)
實際開發中建議使用線程池(如ExecutorService
),避免頻繁創建/銷毀線程開銷:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(() -> System.out.println("線程池任務"));
executor.shutdown(); // 關閉線程池
三種方式對比
方式 | 優點 | 缺點 |
---|---|---|
繼承 Thread | 簡單直接 | 無法繼承其他類 |
實現 Runnable | 靈活、可擴展 | 無返回值 |
實現 Callable | 支持返回值和異常 | 需配合 FutureTask 使用 |
根據需求選擇合適的方式,優先推薦 Runnable
或 Callable
!