開始使用免費開始

為批次處理實作執行緒池

想像你正在開發一個文件處理系統,需要同時處理多個文件。每個文件都需要密集的處理,且應並行執行;但你也希望限制同時進行的作業數量,以避免系統過載。你將使用 ExecutorService 來實作解決方案,讓處理工作量能被有效管理。

本練習屬於課程

Java 程式碼最佳化

檢視課程

練習說明

  • 建立一個包含 3 條執行緒的固定執行緒池。
  • processDocument(doc) 方法以任務形式提交給 executor。
  • 在不強制立刻終止的情況下關閉 executor(shutdown)。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

public class DocumentProcessor {
    public static void main(String[] args) throws InterruptedException {
        List documents = List.of("Doc1", "Doc2", "Doc3", "Doc4", "Doc5");
        List> futures = new ArrayList<>();
        
        // Create a fixed thread pool with 3 threads
        ExecutorService executor = Executors.____(____);

        for (String doc : documents) {
            // Submit the processDocument() method to the executor
            futures.add(executor.submit(() -> ____(____)));
        }
        
        // Shutdown the executor and wait for termination
        executor.____();
        executor.awaitTermination(10, TimeUnit.SECONDS);
        
        try {
            for (Future future : futures) {
                System.out.println(future.get());
            }
        } catch (ExecutionException e) {
            System.out.println("Error processing documents: " + e.getMessage());
        }
    }

    private static String processDocument(String docId) throws InterruptedException {
        System.out.println("Processing " + docId + " on thread " + Thread.currentThread().getName());
        Thread.sleep((long) (Math.random() * 1000));
        return docId + " Processed";
    }
}
編輯並執行程式碼