java多线程(11) Future与CompletableFuture

博客围绕Java并发异步编程展开,指出Java的Future在执行get时会阻塞,直到获取返回结果才执行后续逻辑,这与JS中的异步不同。而使用CompletableFuture可改善这一情况,实现更理想的并发异步编程。

参考:搞定 CompletableFuture,并发异步编程和编写串行程序还有什么区别?你们要的多图长文
java的future在执行get时是会阻塞的,直到拿到返回结果才会执行后面的逻辑,这和js中的axiso异步不同,并不是我们想要的:

public class FutureDemo1 {
    public static void main(String[] args) {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), threadFactory);
        FutureRunnable runnable = new FutureRunnable();
        Future<?> submit = threadPoolExecutor.submit(runnable);
        try {
            submit.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
        System.out.println("程序结束");
        while (true) {
            if (Thread.currentThread().isInterrupted()) {
                threadPoolExecutor.shutdown();
                break;
            }
        }
    }
}

class FutureRunnable implements Runnable {
    @Override
    public void run() {
        try {
            System.out.println("程序正在运行");
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("报错了!");
    }
}

使用了CompletableFuture后:

public class FutureDemo2 {
    public static void main(String[] args) {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 10,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(), threadFactory);
        FutureRunnable2 runnable2 = new FutureRunnable2();
        CompletableFuture.runAsync(runnable2, threadPoolExecutor)
                .whenComplete((aVoid, throwable) -> System.out.println("程序A结束"))
                .exceptionally(throwable -> {
                    throwable.printStackTrace();
                    runnable2.flg = false;
                    return null;
                });
        System.out.println("我在A执行后,A报错前执行");
        while (true) {
            if (!runnable2.flg) {
                threadPoolExecutor.shutdown();
                break;
            }
        }
    }
}

class FutureRunnable2 implements Runnable {
    volatile boolean flg = true;

    @Override
    public void run() {
        try {
            System.out.println("程序A正在运行");
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("A报错了!");

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值