文章最後更新於 2024 年 6 月 11 日
在Java中,多執行緒機制是一種允許多個執行緒同時運行的技術。多執行緒可以提高程序的性能,尤其在處理大量獨立任務時。下面是對Java多執行緒機制的簡要解釋:
1. 創建執行緒
在Java中,可以通過兩種方式創建執行緒:
- 繼承Thread類:
class MyThread extends Thread {
public void run() {
System.out.println("My thread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread t1 = new MyThread();
t1.start();
}
}
- 實現Runnable接口:
class MyRunnable implements Runnable {
public void run() {
System.out.println("My runnable is running");
}
}
public class Main {
public static void main(String[] args) {
Thread t2 = new Thread(new MyRunnable());
t2.start();
}
}
3.使用Callable和Future:
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class MyCallable implements Callable<String> {
public String call() throws Exception {
return "Task completed";
}
}
public class TestCallable {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newFixedThreadPool(1);
MyCallable myCallable = new MyCallable();
Future<String> future = executor.submit(myCallable);
System.out.println(future.get()); // 取得返回值
executor.shutdown();
}
}
優點:可以返回結果或拋出異常。
缺點:需要使用ExecutorService來管理。
2. 執行緒的生命周期
執行緒有五個主要狀態:
- 新建(New):執行緒對象已經創建,但還沒有調用start()方法。
- 就緒(Runnable):調用了start()方法,等待CPU調度執行。
- 運行(Running):正在執行run()方法的程式碼。
- 阻塞(Blocked):等待某個資源或者鎖。
- 死亡(Dead):run()方法執行完畢,或者因為異常終止。
3. 執行緒的同步
當多個執行緒訪問共享資源時,可能會發生數據不一致的問題。為了解決這個問題,可以使用同步(synchronized)機制:
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) counter.increment();
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Count: " + counter.getCount()); // 期望輸出為2000
}
}
比較表
| 方法 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| 繼承Thread | 簡單易用 | 無法繼承其他類 | 單一執行緒任務 |
| 實現Runnable | 可以繼承其他類 | 需要手動創建Thread對象 | 多個執行緒任務 |
| Callable | 可以返回結果或拋出異常 | 需要使用ExecutorService | 任務需要返回結果或異常處理 |
| synchronized | 簡單直接的同步方式 | 可能導致性能問題(例如死鎖) | 簡單同步需求 |
4. 執行緒通信
Java提供了wait()、notify()和notifyAll()方法來實現執行緒之間的通信,這些方法必須在同步塊(synchronized block)中調用。
結語
多執行緒是一種複雜但強大的機制,可以顯著提升程序性能。在使用多執行緒時,需要注意同步問題,確保程序的正確性和穩定性。
關於作者

-
大家好,我是 Oscar(卡哥)。曾任 Yahoo 資深工程師(Lead Engineer),也是高智商組織 Mensa 的會員,擁有超過 15 年的軟體開發經驗。職涯中曾參與 Yahoo 關鍵字廣告、電子商務與搜尋相關專案,近年則在虛擬貨幣交易所專注於大數據與 AI 資料服務,帶領團隊開發具影響力的產品與解決方案。
在工作之外,我熱愛音樂,平時喜歡彈吉他、創作與演奏;運動方面偏好羽球、高爾夫球,也投入在美股與虛擬貨幣的投資領域。最享受的,是透過交流與分享,把知識與經驗轉化成更多可能性。
最新文章
- 2026 年 7 月 5 日高併發系統設計服務韌性設計模式:Bulkhead、RateLimiter 與更多
- 2025 年 10 月 12 日Scrum 方法論為什麼 Scrum 團隊會失敗?——從「儀式」回到「實戰」的長期觀察與修復手冊
- 2025 年 8 月 17 日軟體開發最佳實踐【軟體開發必讀】程式人生中的七大浪費:你是不是天天在做白工?
- 2025 年 2 月 8 日人工智能(AI)高效使用DeepSeek R1的7個核心技巧與地雷提示詞解析|2025實戰指南