เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การสร้าง thread pool สำหรับการประมวลผลแบบ batch

สมมติว่ากำลังพัฒนาระบบประมวลผลเอกสารที่ต้องจัดการเอกสารหลายรายการพร้อมกัน เอกสารแต่ละฉบับต้องใช้การประมวลผลที่เข้มข้นและควรทำแบบขนาน แต่ต้องการจำกัดจำนวนการดำเนินการที่เกิดขึ้นพร้อมกันเพื่อป้องกันไม่ให้ระบบรับภาระมากเกินไป ในแบบฝึกหัดนี้จะใช้ ExecutorService เพื่อบริหารจัดการปริมาณงานการประมวลผลได้อย่างมีประสิทธิภาพ

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

การปรับแต่งโค้ดใน Java

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้าง fixed thread pool ที่มี 3 threads
  • ส่งเมธอด processDocument(doc) เป็น task ให้กับ executor
  • สั่งปิด executor โดยไม่บังคับหยุดการทำงานทันที

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

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";
    }
}
แก้ไขและรันโค้ด