一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Java8 自定義CompletableFuture的原理解析

Java8 自定義CompletableFuture的原理解析

2022-03-11 10:25小小工匠 Java教程

這篇文章主要介紹了Java8 自定義CompletableFuture的原理解析,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

Java8 自定義CompletableFuture原理

Future 接口 的局限性有很多,其中一個就是需要主動的去詢問是否完成,如果等子線程的任務(wù)完成以后,通知我,那豈不是更好?

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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.setCompletable(new Completable<String>() {
            @Override
            public void complete(String s) {
                System.out.println("complete 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 Completable<T> completable;
            @Override
            public T get() {
                return result.get();
            }
            @Override
            public boolean isDone() {
                return finished.get();
            }
            // 設(shè)置完成
            @Override
            public void setCompletable(Completable<T> completable) {
                this.completable = completable;
            }
            // 獲取
            @Override
            public Completable<T> getCompletable() {
                return completable;
            }
        };
        Thread t = new Thread(() -> {
            try {
                T value = callable.action();
                result.set(value);
                finished.set(true);
                if (future.getCompletable() != null)
                    future.getCompletable().complete(value);
            } catch (Throwable cause) {
                if (future.getCompletable() != null)
                    future.getCompletable().exception(cause);
            }
        });
        t.start();
        return future;
    }
    private interface Future<T> {
        T get();
        boolean isDone();
        //  1
        void setCompletable(Completable<T> completable);
        //  2
        Completable<T> getCompletable();
    }
    private interface Callable<T> {
        T action();
    }
    // 回調(diào)接口
    private interface Completable<T> {
        void complete(T t);
        void exception(Throwable cause);
    }
}

Java8 自定義CompletableFuture的原理解析

CompleteFuture簡單使用

Java8 中的 completeFuture 是對 Future 的擴展實現(xiàn), 主要是為了彌補 Future 沒有相應(yīng)的回調(diào)機制的缺陷.

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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  2019/4/22 10:23
 * @E-Mail [email protected]
 */
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 "異步任務(wù)計算結(jié)果!";
        });
        // 提交完異步任務(wù)后, 主線程可以繼續(xù)干一些其他的事情.
        doSomeThingElse();
        // 為了獲取異步計算結(jié)果, 我們可以通過 future.get 和 輪詢機制來獲取.
        String result;
        // Get 方式會導(dǎo)致當(dāng)前線程阻塞, 這顯然違背了異步計算的初衷.
        // result = future.get();
        // 輪詢方式雖然不會導(dǎo)致當(dāng)前線程阻塞, 但是會導(dǎo)致高額的 CPU 負載.
        long start = System.currentTimeMillis();
        while (true) {
            if (future.isDone()) {
                break;
            }
        }
        System.out.println("輪詢耗時:" + (System.currentTimeMillis() - start));       
        result = future.get();
        System.out.println("獲取到異步計算結(jié)果啦: " + result);
        cachePool.shutdown();
    }
    private static void doSomeThingElse() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("我的最重要的事情干完了, 我要獲取異步計算結(jié)果來執(zhí)行剩下的事情.");
    }
}

輸出:

我的最重要的事情干完了, 我要獲取異步計算結(jié)果來執(zhí)行剩下的事情.
輪詢耗時:2000
獲取到異步計算結(jié)果啦: 異步任務(wù)計算結(jié)果!

Process finished with exit code 0

從上面的 Demo 中我們可以看出, future 在執(zhí)行異步任務(wù)時, 對于結(jié)果的獲取顯的不那么優(yōu)雅, 很多第三方庫就針對 Future 提供了回調(diào)式的接口以用來獲取異步計算結(jié)果, 如Google的: ListenableFuture, 而 Java8 所提供的 CompleteFuture 便是官方為了彌補這方面的不足而提供的 API.

下面簡單介紹用法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package demos;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * @author djh on  2019/5/1 20:26
 * @E-Mail [email protected]
 */
public class CompleteFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> completableFutureOne = new CompletableFuture<>();
        ExecutorService cachePool = Executors.newCachedThreadPool();
        cachePool.execute(() -> {
            try {
                Thread.sleep(3000);
                completableFutureOne.complete("異步任務(wù)執(zhí)行結(jié)果");
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        // WhenComplete 方法返回的 CompletableFuture 仍然是原來的 CompletableFuture 計算結(jié)果.
        CompletableFuture<String> completableFutureTwo = completableFutureOne.whenComplete((s, throwable) -> {
            System.out.println("當(dāng)異步任務(wù)執(zhí)行完畢時打印異步任務(wù)的執(zhí)行結(jié)果: " + s);
        });
        // ThenApply 方法返回的是一個新的 completeFuture.
        CompletableFuture<Integer> completableFutureThree = completableFutureTwo.thenApply(s -> {
            System.out.println("當(dāng)異步任務(wù)執(zhí)行結(jié)束時, 根據(jù)上一次的異步任務(wù)結(jié)果, 繼續(xù)開始一個新的異步任務(wù)!");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return s.length();
        });
        System.out.println("阻塞方式獲取執(zhí)行結(jié)果:" + completableFutureThree.get());
        cachePool.shutdown();
    }
}

從上面的 Demo 中我們主要需要注意 thenApply 和 whenComplete 這兩個方法, 這兩個方法便是 CompleteFuture 中最具有意義的方法, 他們都會在 completeFuture 調(diào)用 complete 方法傳入異步計算結(jié)果時回調(diào), 從而獲取到異步任務(wù)的結(jié)果.

相比之下 future 的阻塞和輪詢方式獲取異步任務(wù)的計算結(jié)果, CompleteFuture 獲取結(jié)果的方式就顯的優(yōu)雅的多。

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。

原文鏈接:https://artisan.blog.csdn.net/article/details/115450097

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 美女全身体光羞羞漫画 | 思思99热久久精品在2019线 | 17岁俄罗斯csgo | 黄瓜视频黄 | 亚洲国产中文字幕在线视频综合 | 欧美一区精品二区三区 | 男人午夜视频在线观看 | aaa黄色| 国产精品久久国产三级国电话系列 | 国产日韩精品一区二区在线观看 | 男人都懂www深夜免费网站 | 九九热视频免费 | 日本久久影视 | 幻女free性俄罗斯第一次摘花 | 国产成人精品一区二区 | 日韩精品免费一区二区三区 | 男人天堂久久 | 国产精品99久久免费观看 | 亚洲网红精品大秀在线观看 | 亚裔aⅴ艳星katsuni | 国产情侣啪啪 | 午夜精品国产 | 国产青草亚洲香蕉精品久久 | 99视频有精品 | 美女在线看永久免费网址 | 国产激情影院 | 国产欧美一区二区三区久久 | 亚洲天天做夜夜做天天欢 | 欧美透逼视频 | 美国大片成人性网 | 天堂资源wwww在线看 | 奇米影视久久 | 国产一区二区免费在线 | 日本小视频免费 | 国产精品在线 | 国产成人综合久久 | juy799大岛优香在线观看 | 国产成人综合亚洲亚洲欧美 | 婷婷色综合网 | 欧美日韩高清观看一区二区 | 国产精品免费_区二区三区观看 |