@@ -23,28 +23,27 @@ public static void main(String[] args) {
23
23
public static void allOfGet () {
24
24
//该线程池仅用于示例,实际建议使用自定义的线程池
25
25
ExecutorService executorService = Executors .newCachedThreadPool ();
26
- String word1 = "word1" ;
27
- String word2 = "word2" ;
28
26
29
27
//线程安全的list,适合写多读少的场景
30
- List <String > strList = Collections .synchronizedList (new ArrayList <>(50 ));
28
+ List <String > resultList = Collections .synchronizedList (new ArrayList <>(50 ));
31
29
CompletableFuture <String > completableFuture1 = CompletableFuture .supplyAsync (
32
- () -> getResult ( word1 , 1000 ), executorService )
30
+ () -> runTask ( "result1" , 1000 ), executorService )
33
31
.whenComplete ((result , throwable ) -> {
34
- //任务完成时执行
32
+ //任务完成时执行。用list存放任务的返回值
35
33
if (result != null ) {
36
- strList .add (result );
34
+ resultList .add (result );
37
35
}
36
+ //触发异常
38
37
if (throwable != null ) {
39
38
logger .error ("completableFuture1 error:{}" , throwable );
40
39
}
41
40
});
42
41
43
42
CompletableFuture <String > completableFuture2 = CompletableFuture .supplyAsync (
44
- () -> getResult ( word2 , 1500 ), executorService )
43
+ () -> runTask ( "result2" , 1500 ), executorService )
45
44
.whenComplete ((result , throwable ) ->{
46
45
if (result != null ) {
47
- strList .add (result );
46
+ resultList .add (result );
48
47
}
49
48
if (throwable != null ) {
50
49
logger .error ("completableFuture2 error:{}" , throwable );
@@ -57,27 +56,29 @@ public static void allOfGet() {
57
56
futureList .add (completableFuture2 );
58
57
59
58
try {
60
- //多个任务,耗时不超时2秒
61
- CompletableFuture .allOf (futureList .toArray (new CompletableFuture [0 ]))
62
- .get (2 , TimeUnit .SECONDS );
63
- } catch (InterruptedException | ExecutionException e ) {
64
- logger .error ("CompletableFuture.allOf InterruptedException error." , e );
65
- } catch (TimeoutException e ) {
66
- logger .error ("CompletableFuture.allOf TimeoutException error." , e );
59
+ //多个任务
60
+ CompletableFuture [] futureArray = futureList .toArray (new CompletableFuture [0 ]);
61
+ //将多个任务,汇总成一个任务,总共耗时不超时2秒
62
+ CompletableFuture .allOf (futureArray ).get (2 , TimeUnit .SECONDS );
63
+ } catch (Exception e ) {
64
+ logger .error ("CompletableFuture.allOf Exception error." , e );
67
65
}
68
- List <String > resultList = new ArrayList <>(strList );
66
+ List <String > list = new ArrayList <>(resultList );
69
67
70
- resultList .forEach (System .out ::println );
68
+ list .forEach (System .out ::println );
71
69
}
72
70
73
71
74
- private static String getResult (String result , int millis ) {
72
+ private static String runTask (String result , int millis ) {
75
73
try {
74
+ //此处忽略实际的逻辑,用sleep代替
76
75
//任务耗时。可以分别设置1000和3000,看未超时和超时的不同结果。
77
76
Thread .sleep (millis );
78
77
} catch (InterruptedException e ) {
79
78
logger .error ("supplyAsyncGet error." );
80
79
}
81
80
return result ;
82
81
}
82
+
83
+
83
84
}
0 commit comments