Future -> 代表的是未來的一個憑據
1
2
3
|
public interface Future<T> { T get() throws InterruptedException; } |
AsynFuture -> 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
|
public class AsynFuture<T> implements Future<T> { private volatile boolean done = false ; private T result; public void done(T result){ synchronized ( this ){ this .result = result; this .done = true ; this .notifyAll(); } } /** * 輪詢 沒有完成等待 */ @Override public T get() throws InterruptedException { synchronized ( this ) { while (!done) { this .wait(); } } return result; } } |
FutureService -> 橋接Future和FutureTask
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
|
public class FutureService { /** * 需進程等待 */ public <T> Future<T> submit( final FutureTask<T> task) { AsynFuture<T> asynFuture = new AsynFuture<>(); new Thread(() -> { T result = task.call(); asynFuture.done(result); }).start(); return asynFuture; } /** * 運行完 自動回調 * 無需進程等待 */ public <T> Future<T> submit( final FutureTask<T> task, final Consumer<T> consumer) { AsynFuture<T> asynFuture = new AsynFuture<>(); new Thread(() -> { T result = task.call(); asynFuture.done(result); consumer.accept(result); }).start(); return asynFuture; } } |
FutureTask -> 將你的調用邏輯進行了隔離
1
2
3
4
|
public interface FutureTask<T> { T call(); } |
需要時回調:
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
|
/** * Future -> 代表的是未來的一個憑據 * FutureTask -> 將你的調用邏輯進行了隔離 * FutureService -> 橋接Future和FutureTask */ public class SyncInvoker { public static void main(String[] args) throws InterruptedException { FutureService futureService = new FutureService(); Future<String> future = futureService.submit(() -> { try { Thread.sleep( 10001 ); } catch (InterruptedException e) { e.printStackTrace(); } return "FINISH" ; }); System.out.println( "==============" ); System.out.println( "do other thing." ); Thread.sleep( 1000 ); System.out.println( "==============" ); /** * 調用也形成了阻塞 */ System.out.println(future.get()); } } |
運行:
==============
do other thing.
==============
FINISH
運行完自動回調:
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
|
//** * Future -> 代表的是未來的一個憑據 * FutureTask -> 將你的調用邏輯進行了隔離 * FutureService -> 橋接Future和FutureTask */ public class SyncInvoker { public static void main(String[] args) throws InterruptedException { FutureService futureService = new FutureService(); futureService.submit(() -> { try { Thread.sleep( 10001 ); } catch (InterruptedException e) { e.printStackTrace(); } return "FINISH" ; },System.out::println); System.out.println( "==============" ); System.out.println( "do other thing." ); Thread.sleep( 1000 ); System.out.println( "==============" ); } } |
到此這篇關于Java多線程之Future設計模式的文章就介紹到這了,更多相關Java多線程 Future內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://juejin.cn/post/7022215197204938783