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

服務器之家:專注于服務器技術及軟件下載分享
分類導航

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

服務器之家 - 編程語言 - Java教程 - Java8新的異步編程方式CompletableFuture實現

Java8新的異步編程方式CompletableFuture實現

2021-07-28 12:11will的猜想 Java教程

這篇文章主要介紹了Java8新的異步編程方式CompletableFuture實現,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

一. future

jdk 5引入了future模式。future接口是java多線程future模式的實現,在java.util.concurrent包中,可以來進行異步計算。

future模式是多線程設計常用的一種設計模式。future模式可以理解成:我有一個任務,提交給了future,future替我完成這個任務。期間我自己可以去做任何想做的事情。一段時間之后,我就便可以從future那兒取出結果。

future的接口很簡單,只有五個方法。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
public interface future<v> {
 
 boolean cancel(boolean mayinterruptifrunning);
 
 boolean iscancelled();
 
 boolean isdone();
 
 v get() throws interruptedexception, executionexception;
 
 v get(long timeout, timeunit unit)
  throws interruptedexception, executionexception, timeoutexception;
}

future接口的方法介紹如下:

  • boolean cancel (boolean mayinterruptifrunning) 取消任務的執行。參數指定是否立即中斷任務執行,或者等等任務結束
  • boolean iscancelled () 任務是否已經取消,任務正常完成前將其取消,則返回 true
  • boolean isdone () 任務是否已經完成。需要注意的是如果任務正常終止、異常或取消,都將返回true
  • v get () throws interruptedexception, executionexception 等待任務執行結束,然后獲得v類型的結果。interruptedexception 線程被中斷異常, executionexception任務執行異常,如果任務被取消,還會拋出cancellationexception
  • v get (long timeout, timeunit unit) throws interruptedexception, executionexception, timeoutexception 同上面的get功能一樣,多了設置超時時間。參數timeout指定超時時間,uint指定時間的單位,在枚舉類timeunit中有相關的定義。如果計 算超時,將拋出timeoutexception

一般情況下,我們會結合callable和future一起使用,通過executorservice的submit方法執行callable,并返回future。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
executorservice executor = executors.newcachedthreadpool();
 
future<string> future = executor.submit(() -> { //lambda 是一個 callable, 提交后便立即執行,這里返回的是 futuretask 實例
 system.out.println("running task");
 thread.sleep(10000);
 return "return task";
});
 
try {
 thread.sleep(1000);
} catch (interruptedexception e) {
}
 
system.out.println("do something else"); //前面的的 callable 在其他線程中運行著,可以做一些其他的事情
 
try {
 system.out.println(future.get()); //等待 future 的執行結果,執行完畢之后打印出來
} catch (interruptedexception e) {
} catch (executionexception e) {
 
} finally {
 executor.shutdown();
}

比起future.get(),其實更推薦使用get (long timeout, timeunit unit) 方法,設置了超時時間可以防止程序無限制的等待future的結果。

二. completablefuture介紹

2.1 future模式的缺點

future雖然可以實現獲取異步執行結果的需求,但是它沒有提供通知的機制,我們無法得知future什么時候完成。

要么使用阻塞,在future.get()的地方等待future返回的結果,這時又變成同步操作。要么使用isdone()輪詢地判斷future是否完成,這樣會耗費cpu的資源。

2.2 completablefuture介紹

netty、guava分別擴展了java 的 future 接口,方便異步編程。

java 8新增的completablefuture類正是吸收了所有google guava中listenablefuture和settablefuture的特征,還提供了其它強大的功能,讓java擁有了完整的非阻塞編程模型:future、promise 和 callback(在java8之前,只有無callback 的future)。

completablefuture能夠將回調放到與任務不同的線程中執行,也能將回調作為繼續執行的同步函數,在與任務相同的線程中執行。它避免了傳統回調最大的問題,那就是能夠將控制流分離到不同的事件處理器中。

completablefuture彌補了future模式的缺點。在異步的任務完成后,需要用其結果繼續操作時,無需等待。可以直接通過thenaccept、thenapply、thencompose等方式將前面異步處理的結果交給另外一個異步事件處理線程來處理。

三. completablefuture特性

3.1 completablefuture的靜態工廠方法

 

方法名 描述
runasync(runnable runnable) 使用forkjoinpool.commonpool()作為它的線程池執行異步代碼。
runasync(runnable runnable, executor executor) 使用指定的thread pool執行異步代碼。
supplyasync(supplier<u> supplier) 使用forkjoinpool.commonpool()作為它的線程池執行異步代碼,異步操作有返回值
supplyasync(supplier<u> supplier, executor executor) 使用指定的thread pool執行異步代碼,異步操作有返回值

 

runasync 和 supplyasync 方法的區別是runasync返回的completablefuture是沒有返回值的。    

?
1
2
3
4
5
6
7
8
9
10
11
12
13
completablefuture<void> future = completablefuture.runasync(() -> {
     system.out.println("hello");
   });
 
   try {
     future.get();
   } catch (interruptedexception e) {
     e.printstacktrace();
   } catch (executionexception e) {
     e.printstacktrace();
   }
 
   system.out.println("completablefuture");

而supplyasync返回的completablefuture是由返回值的,下面的代碼打印了future的返回值。

?
1
2
3
4
5
6
7
8
9
10
11
completablefuture<string> future = completablefuture.supplyasync(() -> "hello");
 
try {
  system.out.println(future.get());
} catch (interruptedexception e) {
  e.printstacktrace();
} catch (executionexception e) {
  e.printstacktrace();
}
 
system.out.println("completablefuture");

3.2 completable

 

方法名 描述
complete(t t) 完成異步執行,并返回future的結果
completeexceptionally(throwable ex) 異步執行不正常的結束

 

future.get()在等待執行結果時,程序會一直block,如果此時調用complete(t t)會立即執行。

?
1
2
3
4
5
6
7
8
9
10
11
completablefuture<string> future = completablefuture.supplyasync(() -> "hello");
 
future.complete("world");
 
try {
  system.out.println(future.get());
} catch (interruptedexception e) {
  e.printstacktrace();
} catch (executionexception e) {
  e.printstacktrace();
}

執行結果:

world

可以看到future調用complete(t t)會立即執行。但是complete(t t)只能調用一次,后續的重復調用會失效。

如果future已經執行完畢能夠返回結果,此時再調用complete(t t)則會無效。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
completablefuture<string> future = completablefuture.supplyasync(() -> "hello");
 
try {
  thread.sleep(5000);
} catch (interruptedexception e) {
  e.printstacktrace();
}
 
future.complete("world");
 
try {
  system.out.println(future.get());
} catch (interruptedexception e) {
  e.printstacktrace();
} catch (executionexception e) {
  e.printstacktrace();
}

執行結果:

hello

如果使用completeexceptionally(throwable ex)則拋出一個異常,而不是一個成功的結果。

?
1
2
3
4
5
6
7
8
9
10
11
completablefuture<string> future = completablefuture.supplyasync(() -> "hello");
 
future.completeexceptionally(new exception());
 
try {
  system.out.println(future.get());
} catch (interruptedexception e) {
  e.printstacktrace();
} catch (executionexception e) {
  e.printstacktrace();
}

執行結果:

java.util.concurrent.executionexception: java.lang.exception
...

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 日本高清免费观看 | 久久r视频 | 动漫精品午夜在线播放 | 三级视频中文字幕 | 我和岳偷长篇小说 | 短篇最污的乱淫伦小说全集 | 91九色丨porny丨制服 | 羞羞污视频 | 高清视频在线播放ww | 亚洲精品综合一区二区 | www.俺去啦 | 丝袜护士强制脚足取精 | 99久久爱热6在线播放 | 日韩影院在线观看 | 九九精品视频一区二区三区 | 国产不卡视频一区二区在线观看 | 女子监狱第二季未删减在线看 | 大又大又粗又爽女人毛片 | 四虎在线免费播放 | 亚洲国产成人综合 | 精品国产一区二区三区在线观看 | 国产精品国产三级国产专区不 | 99国内精品久久久久久久黑人 | 美女视频ww8888网网 | 亚洲欧美影院 | 91免费在线播放 | 色婷婷六月丁香在线观看 | 日本偷拍xxxxxxww | 女子监狱第二季未删减在线看 | 国产精品久久久久久久久久久久久久 | 韩国最新三级网站在线播放 | 天天综合天天影视色香欲俱全 | 激情三级做爰在线观看激情 | 国产精品久久免费 | 鸭子玩富婆流白浆视频 | 亚洲第一福利视频 | 456在线观看 | 国产乱码一卡二卡3卡四卡 国产乱插 | 催眠 迷j系列小说 | 日韩av线观看 | 日韩专区在线观看 |