MST

星途 面试题库

面试题:Java中CompletableFuture如何设置自定义线程池饱和策略

在Java的CompletableFuture使用场景下,当你需要自定义线程池并设置饱和策略时,简述如何通过代码实现?请给出关键步骤和示例代码。
21.0万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 关键步骤
    • 创建ThreadPoolExecutor实例,用于自定义线程池。在构造函数中设置核心线程数、最大线程数、存活时间、任务队列以及饱和策略。
    • 使用CompletableFuturesupplyAsyncrunAsync等方法时,将自定义的ThreadPoolExecutor实例作为参数传入,这样CompletableFuture就会使用自定义线程池来执行异步任务。
  2. 示例代码
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

public class CompletableFutureCustomThreadPool {
    public static void main(String[] args) {
        // 创建自定义线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, // 核心线程数
                4, // 最大线程数
                10, TimeUnit.SECONDS, // 线程存活时间
                new ArrayBlockingQueue<>(5), // 任务队列
                new ThreadFactory() {
                    private final AtomicInteger threadNumber = new AtomicInteger(1);
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r, "Custom-Thread-" + threadNumber.getAndIncrement());
                        thread.setDaemon(false);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()); // 饱和策略

        // 使用自定义线程池执行CompletableFuture任务
        CompletableFuture.supplyAsync(() -> {
            System.out.println("任务在自定义线程池线程 " + Thread.currentThread().getName() + " 中执行");
            return "任务执行结果";
        }, executor)
       .thenAccept(System.out::println)
       .join();

        // 关闭线程池
        executor.shutdown();
    }
}

在上述代码中:

  • 首先通过ThreadPoolExecutor的构造函数创建了一个自定义线程池,设置了核心线程数为2,最大线程数为4,线程存活时间为10秒,任务队列容量为5,线程工厂自定义线程名称,饱和策略为CallerRunsPolicy(当线程池和队列都满时,由调用者线程来执行任务)。
  • 然后使用CompletableFuture.supplyAsync方法执行异步任务,并将自定义线程池executor作为参数传入。最后通过thenAccept处理任务结果并使用join等待任务完成。
  • 最后调用executor.shutdown()关闭线程池。