解釋Java中的多執行緒機制

文章最後更新於 2024 年 6 月 11 日

在Java中,多執行緒機制是一種允許多個執行緒同時運行的技術。多執行緒可以提高程序的性能,尤其在處理大量獨立任務時。下面是對Java多執行緒機制的簡要解釋:

1. 創建執行緒

在Java中,可以通過兩種方式創建執行緒:

  1. 繼承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();
    }
}

  1. 實現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.使用CallableFuture

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 資料服務,帶領團隊開發具影響力的產品與解決方案。

在工作之外,我熱愛音樂,平時喜歡彈吉他、創作與演奏;運動方面偏好羽球、高爾夫球,也投入在美股與虛擬貨幣的投資領域。最享受的,是透過交流與分享,把知識與經驗轉化成更多可能性。