开始使用免费开始使用

为批处理实现线程池

假设您正在开发一个文档处理系统,需要同时处理多个文档。每个文档都需要密集的处理,并且应并行执行,但您希望限制并发操作的数量以避免系统过载。您将使用 ExecutorService 来实现一个方案,高效管理处理负载。

本练习是课程的一部分

Java 代码优化

查看课程

练习说明

  • 创建一个包含 3 个线程的固定线程池。
  • processDocument(doc) 方法作为任务提交给执行器。
  • 关闭执行器,但不要立刻强制终止。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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";
    }
}
编辑并运行代码