java异步对象Future和CompletableFuture

java如何创建异步任务

public class TestThread {

    public static void main(String[] args) {
        Runnable task = () -> {
            System.out.println("异步执行");
        };
        new Thread(task).start();

        System.out.println("同步执行");
    }
    
}

在java中执行异步任务需要新建一个Thread线程,然后通过Runnable接口实现一个任务,最后将任务通过参数的方式传递给Thread类。

获取异步任务的的结果

public class TestThread {

    public static void main(String[] args) {
        // 结果集合
        List<String> pdfList = new LinkedList<>();
        
        // 异步任务
        Runnable task = () -> {
            String pdf = downloadPdf();
            // 将结果放入list
            pdfList.add(pdf);
        };
        new Thread(task).start();
        
        // 输出结果集合的大小
        System.out.println(pdfList.size());
    }

    private static String downloadPdf() {
        return "pdf";
    }

}

上面这种方式获取异步执行结果是有问题的,输出集合的大小可能为0,这是因为在输出结果的时候异步任务可能还没开始执行。

Future解决了什么问题

为了能够在获取到异步任务执行的结果后再继续之后的代码,我们可以使用CountDownLatch或者FutureTask,因为本篇内容是讲Future,所以仅说明Future的使用方法。

为了解决Runnable不能适配没有返回值的问题,jdk使用适配器模式为我们实现了FutureTask类,FutureTask实现了Runnable接口和Future接口

public class TestThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 结果集合
        List<String> pdfList = new LinkedList<>();

        // 异步任务
        FutureTask<String> task = new FutureTask(() -> {
            String pdf = downloadPdf();
            // 返回结果
            return pdf;
        });
        new Thread(task).start();
        
        // 等待异步任务执行完成后,添加到集合
        pdfList.add(task.get());
        
        // 输出集合大小
        System.out.println(pdfList.size());
    }

    private static String downloadPdf() {
        return "pdf";
    }

}

通过调用FutureTask的get()方法,当前线程会阻塞等待异步线程执行完成并将结果返回。

CompetableFuture解决了什么问题

了解了FutureTask之后,我们知道FutureTask.get()方法会阻塞当前线程,等待异步执行结果返回。我们来看下面这个例子。

public class TestThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 结果集合
        List<String> pdfList = new LinkedList<>();

        // 异步任务1
        FutureTask<String> task1 = new FutureTask(() -> {
            String pdf = downloadPdf();
            // 返回结果
            return pdf;
        });
        new Thread(task1).start();

        // 异步任务2
        FutureTask<String> task2 = new FutureTask(() -> {
            String pdf = downloadPdf();
            // 返回结果
            return pdf;
        });
        new Thread(task2).start();

        // 异步任务执行完成后,添加到集合
        String pdfFont1 = getFontFromPdf(task1.get());
        String pdfFont2 = getFontFromPdf(task2.get());
        
        pdfList.add(pdfFont1);
        pdfList.add(pdfFont2);

        // 输出集合大小
        System.out.println(pdfList.size());
    }
    
    private static String getFontFromPdf(String pdf) {
        return "pdf-font";
    }

    private static String downloadPdf() {
        return "pdf";
    }

}

String pdfFont1 = getFontFromPdf(task1.get());在执行该代码的时候会等待task1执行完成在继续后面的代码,那么如果task2先执行完成的话就要干等着。

这时候我们可以将getFontFromPdf方法也放到task中如下,这样就能避免这个问题。

// 异步任务
FutureTask<String> task1 = new FutureTask(() -> {
    String pdf = downloadPdf();
    // 返回结果
    return getFontFromPdf(pdf);
});

另外,我们还能通过CompetableFuture来解决这个问题,代码如下

public class TestThread {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 结果集合
        List<String> pdfList = new LinkedList<>();

        // 异步任务1
        CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
            String pdf = downloadPdf();
            // 返回结果
            return pdf;
        }).thenApplyAsync(pdf -> getFontFromPdf(pdf));

        // 异步任务2
        CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
            String pdf = downloadPdf();
            // 返回结果
            return pdf;
        }).thenApplyAsync(pdf -> getFontFromPdf(pdf));

        pdfList.add(task1.get());
        pdfList.add(task2.get());

        // 输出集合大小
        System.out.println(pdfList.size());
    }

    private static String getFontFromPdf(String pdf) {
        return "pdf-font";
    }

    private static String downloadPdf() {
        return "pdf";
    }

}

CompletableFuture通过thenApplyAsync方法追加了对方法结果的二次处理,CompletableFuture是jdk8的新特性,设计更符合lamda的流编程。

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值