一. 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
...
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。