Java 8异步任务类库——CompletableFuture简单介绍和使用

一、直接看代码

package CompletableFuture;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * @author hs
 * @date 2021/11/26 10:23
 * java8新特性
 * CompletableFuture就是用于Java中的异步编程。使用CompletableFuture创建的任务,不会阻塞主线程/主线程不需要等待任务完成,极大地提高了程序的性能
 */
public class CompletableFutureTest {
    public static void main(String[] args)  {
        System.out.println("主线程:["+Thread.currentThread().getName()+"]开始执行----");
        System.out.println("创建异步任务00");
        CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(()->{
            System.out.println("线程:["+Thread.currentThread().getName()+"]开始执行,异步任务被调用");
            //模拟MP4上传
            int progress = 0;
            while (progress <= 100) {
                int i = new Random().nextInt(10);
                progress += i;
                System.out.println(progress + "%");
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "http://www.xxxx.mp4";
        });
        completableFuture.thenAccept(s->System.out.println("上传完成"+s));

        System.out.println("主线程:["+Thread.currentThread().getName()+"]已经执行完毕,处于空闲状态!");

        //如果等待异步任务完成,如果不等待主线程会直接停止运行那么异步任务的线程也会被迫停止。
        while (!completableFuture.isDone()){

        }
    }
}

输出:
在这里插入图片描述

二、参考

CompletableFuture我们可以在什么场景下使用?【想要了解更多推荐阅读】
如果你没有学过lambda表达式推荐阅读这篇

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值