面试题答案
一键面试- 关键步骤:
- 创建
ThreadPoolExecutor
实例,用于自定义线程池。在构造函数中设置核心线程数、最大线程数、存活时间、任务队列以及饱和策略。 - 使用
CompletableFuture
的supplyAsync
或runAsync
等方法时,将自定义的ThreadPoolExecutor
实例作为参数传入,这样CompletableFuture
就会使用自定义线程池来执行异步任务。
- 创建
- 示例代码:
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()
关闭线程池。