Bắt đầu ngayBắt đầu miễn phí

Triển khai thread pool cho xử lý theo lô

Hãy tưởng tượng bạn đang phát triển một hệ thống xử lý tài liệu cần xử lý đồng thời nhiều tài liệu. Mỗi tài liệu đòi hỏi xử lý nặng và nên được thực hiện song song, nhưng bạn muốn giới hạn số lượng tác vụ chạy đồng thời để tránh quá tải hệ thống. Bạn sẽ triển khai giải pháp dùng ExecutorService để quản lý khối lượng xử lý một cách hiệu quả.

Bài tập này là một phần của khóa học

Tối ưu hóa mã trong Java

Xem khóa học

Hướng dẫn bài tập

  • Tạo một fixed thread pool gồm 3 thread.
  • Gửi phương thức processDocument(doc) làm một tác vụ cho executor.
  • Tắt executor mà không ép dừng ngay lập tức.

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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";
    }
}
Chỉnh sửa và Chạy Mã