Java8自定pletableFuture的原理是什么


本篇内容主要讲解“Java8自定pletableFuture的原理是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java8自定pletableFuture的原理是什么”吧!

Java8 自定pletableFuture原理

Future 接口 的局限性有很多,其中一个就是需要主动的去询问是否完成,如果等子线程的任务完成以后,通知我,那岂不是更好?

public class FutureInAction3 {    public static void main(String[] args) {        Future<String> future = invoke(() -> {            try {                Thread.sleep(10000L);                return "I am Finished.";            } catch (InterruptedException e) {                return "I am Error";            }        });        future.sepletable(new&nbsppletable<String>() {            @Override            public void&nbspplete(String s) {                System.out.println(&quotplete called ---- " + s);            }            @Override            public void exception(Throwable cause) {                System.out.println("error");                cause.printStackTrace();            }        });        System.out.println("....do something else .....");        System.out.println("try to get result ->" + future.get());    }    private static <T> Future<T> invoke(Callable<T> callable) {        AtomicReference<T> result = new AtomicReference<>();        AtomicBoolean finished = new AtomicBoolean(false);        Future<T> future = new Future<T>() {            private&nbsppletable<T>&nbsppletable;            @Override            public T get() {                return result.get();            }            @Override            public boolean isDone() {                return finished.get();            }            // 设置完成            @Override            public void sepletablepletable<T>&nbsppletable) {                thispletable =&nbsppletable;            }            // 获取            @Override            public&nbsppletable<T> gepletable() {                return&nbsppletable;            }        };        Thread t = new Thread(() -> {            try {                T value = callable.action();                result.set(value);                finished.set(true);                if (future.gepletable() != null)                    future.gepletable()plete(value);            } catch (Throwable cause) {                if (future.gepletable() != null)                    future.gepletable().exception(cause);            }        });        t.start();        return future;    }    private interface Future<T> {        T get();        boolean isDone();        //  1        void sepletablepletable<T>&nbsppletable);        //  2       &nbsppletable<T> gepletable();    }    private interface Callable<T> {        T action();    }    // 回调接口    private interface&nbsppletable<T> {        void&nbspplete(T t);        void exception(Throwable cause);    }}
<h2pleteFuture简单使用

Java8 中的pleteFuture 是对 Future 的扩展实现, 主要是为了弥补 Future 没有相应的回调机制的缺陷.

我们先看看 Java8 之前的 Future 的使用

package demos;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/** * @author djh on  2022/4/22 10:23 * @E-Mail 1544579459@qq */public class Demo {    public static void main(String[] args) throws ExecutionException, InterruptedException {        ExecutorService cachePool = Executors.newCachedThreadPool();        Future<String> future = cachePool.submit(() -> {            Thread.sleep(3000);            return "异步任务计算结果!";        });        // 提交完异步任务后, 主线程可以继续干一些其他的事情.        doSomeThingElse();        // 为了获取异步计算结果, 我们可以通过 future.get 和 轮询机制来获取.        String result;        // Get 方式会导致当前线程阻塞, 这显然违背了异步计算的初衷.        // result = future.get();        // 轮询方式虽然不会导致当前线程阻塞, 但是会导致高额的 CPU 负载.        long start = System.currentTimeMillis();        while (true) {            if (future.isDone()) {                break;            }        }        System.out.println("轮询耗时:" + (System.currentTimeMillis() - start));                result = future.get();        System.out.println("获取到异步计算结果啦: " + result);        cachePool.shutdown();    }    private static void doSomeThingElse() {        try {            Thread.sleep(1000);        } catch (InterruptedException e) {            e.printStackTrace();        }        System.out.println("我的最重要的事情干完了, 我要获取异步计算结果来执行剩下的事情.");    }}

输出:

我的最重要的事情干完了, 我要获取异步计算结果来执行剩下的事情.
轮询耗时:2000
获取到异步计算结果啦: 异步任务计算结果!

Process finished with exit code 0

从上面的 Demo 中我们可以看出, future 在执行异步任务时, 对于结果的获取显的不那么优雅, 很多第三方库就针对 Future 提供了回调式的接口以用来获取异步计算结果, 如Google的: ListenableFuture, 而 Java8 所提供的pleteFuture 便是官方为了弥补这方面的不足而提供的 API.

下面简单介绍用法

package demos;import java.util.concurrentpletableFuture;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * @author djh on  2022/5/1 20:26 * @E-Mail 1544579459@qq */public class&nbsppleteFutureDemo {    public static void main(String[] args) throws ExecutionException, InterruptedException {       &nbsppletableFuture<String>&nbsppletableFutureOne = new&nbsppletableFuture<>();        ExecutorService cachePool = Executors.newCachedThreadPool();        cachePool.execute(() -> {            try {                Thread.sleep(3000);               &nbsppletableFutureOneplete("异步任务执行结果");                System.out.println(Thread.currentThread().getName());            } catch (InterruptedException e) {                e.printStackTrace();            }        });        // Wheplete 方法返回的&nbsppletableFuture 仍然是原来的&nbsppletableFuture 计算结果.       &nbsppletableFuture<String>&nbsppletableFutureTwo =&nbsppletableFutureOne.wheplete((s, throwable) -> {            System.out.println("当异步任务执行完毕时打印异步任务的执行结果: " + s);        });        // ThenApply 方法返回的是一个新的&nbsppleteFuture.       &nbsppletableFuture<Integer>&nbsppletableFutureThree =&nbsppletableFutureTwo.thenApply(s -> {            System.out.println("当异步任务执行结束时, 根据上一次的异步任务结果, 继续开始一个新的异步任务!");            try {                Thread.sleep(1000);            } catch (InterruptedException e) {                e.printStackTrace();            }            return s.length();        });        System.out.println("阻塞方式获取执行结果:" +&nbsppletableFutureThree.get());        cachePool.shutdown();    }}

从上面的 Demo 中我们主要需要注意 thenApply 和 wheplete 这两个方法, 这两个方法便是pleteFuture 中最具有意义的方法, 他们都会在pleteFuture 调用plete 方法传入异步计算结果时回调, 从而获取到异步任务的结果.

相比之下 future 的阻塞和轮询方式获取异步任务的计算结果,pleteFuture 获取结果的方式就显的优雅的多。

到此,相信大家对“Java8自定pletableFuture的原理是什么”有了更深的了解,不妨来实际操作一番吧!这里是主机评测网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


上一篇:php扩展gd是什么

下一篇:java中set集合的常用方法有哪些


Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器