多執行緒基礎原則

Java 程式碼最佳化

Pavlos Kosmetatos

Lead Engineer @Wealthyhood

序列與平行執行

  • 序列處理 → 逐步執行
  • 平行處理 → 多個操作同時執行

怎麼做到?

  • 現代 CPU 具有多核心
  • 執行緒:程式執行的最小單位
  • 多執行緒 將工作分配到多個核心

單一執行緒像單線道,車子必須依序前進;多執行緒像多線道,車輛可同時通行!

Java 程式碼最佳化

使用執行緒

  • Thread 類別可建立新的執行路徑
  • 每個 Thread 可獨立執行
Runnable task = () -> {
    System.out.println("Processing on thread: " + 
                       Thread.currentThread().getName());
};

Thread thread = new Thread(task);
thread.start();
Processing on thread: Thread-0
Java 程式碼最佳化

多執行緒操作

List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 4; i++) {
    Thread thread = new Thread(() -> System.out.println("Processing data on Thread-" + i));
    threads.add(thread);
    thread.start();
}

for (Thread t : threads) {
    t.join(); // Waits for all threads to complete
}
// Processing data on Thread-0
// Processing data on Thread-2
// Processing data on Thread-1
// Processing data on Thread-3
Java 程式碼最佳化

平行串流(Parallel Streams)

  • Streams:Java 8+ 功能,簡化平行處理
  • 自動處理執行緒的建立與管理
  • 兩種建立方式:
    • collection.parallelStream()
    • Stream.of(...).parallel()
Java 程式碼最佳化

平行串流範例

// Sequential processing
List<Integer> result1 = new ArrayList<>();
for (int i = 0; i < numbers.size(); i++) {
    result1.add(numbers.get(i) * 2);
}

// Sequential processing with stream List<Integer> result2 = numbers.stream() .map(n -> n * 2) .collect(Collectors.toList());
// Parallel processing with parallel stream List<Integer> result3 = numbers.parallelStream() .map(n -> n * 2) .collect(Collectors.toList());
Java 程式碼最佳化

何時使用平行處理

  • CPU 密集的操作
  • 可獨立的資料處理
  • 大型資料集合
  • 可用 CPU 核心數 > 1
  • 下列情況平行化成本可能不划算:
    • 小型資料集
    • 簡單運算
Java 程式碼最佳化

重點總結

  • Thread 類別建立平行執行路徑
  • 用平行串流簡化集合處理
  • 成效取決於:
    • 工作負載型態
    • 資料大小
    • 可用核心數
Java 程式碼最佳化

一起來練習吧!

Java 程式碼最佳化

Preparing Video For Download...