MST
星途 面试题库

面试题:Java中CompletableFuture的thenRunAsync方法基础应用

请简述Java中CompletableFuture的thenRunAsync方法的作用,并且通过代码示例展示如何使用该方法在一个CompletableFuture任务完成后执行一个无返回值的异步任务。
36.5万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试

thenRunAsync方法的作用

CompletableFuturethenRunAsync方法用于在当前CompletableFuture任务完成后,异步执行一个无返回值的Runnable任务。该方法返回一个新的CompletableFuture,当传入的Runnable任务执行完成时,新的CompletableFuture也完成。并且thenRunAsync方法会使用默认的ForkJoinPool.commonPool()线程池来执行Runnable任务,如果需要指定线程池,可以使用thenRunAsync(Runnable runnable, Executor executor)方法。

代码示例

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class CompletableFutureExample {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1开始执行,线程:" + Thread.currentThread().getName());
            // 模拟任务执行
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "任务1完成";
        }).thenRunAsync(() -> {
            System.out.println("任务2开始执行,线程:" + Thread.currentThread().getName());
            // 模拟任务执行
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务2完成");
        }).thenRunAsync(() -> {
            System.out.println("任务3开始执行,线程:" + Thread.currentThread().getName());
            System.out.println("任务3完成");
        }).get();
    }
}

在上述代码中,首先通过supplyAsync创建一个有返回值的异步任务,当这个任务完成后,通过thenRunAsync方法依次执行两个无返回值的异步任务。每个任务执行时会打印当前执行的线程名称,以证明它们是异步执行的。