@@ -23,28 +23,27 @@ public static void main(String[] args) {
2323 public static void allOfGet () {
2424 //该线程池仅用于示例,实际建议使用自定义的线程池
2525 ExecutorService executorService = Executors .newCachedThreadPool ();
26- String word1 = "word1" ;
27- String word2 = "word2" ;
2826
2927 //线程安全的list,适合写多读少的场景
30- List <String > strList = Collections .synchronizedList (new ArrayList <>(50 ));
28+ List <String > resultList = Collections .synchronizedList (new ArrayList <>(50 ));
3129 CompletableFuture <String > completableFuture1 = CompletableFuture .supplyAsync (
32- () -> getResult ( word1 , 1000 ), executorService )
30+ () -> runTask ( "result1" , 1000 ), executorService )
3331 .whenComplete ((result , throwable ) -> {
34- //任务完成时执行
32+ //任务完成时执行。用list存放任务的返回值
3533 if (result != null ) {
36- strList .add (result );
34+ resultList .add (result );
3735 }
36+ //触发异常
3837 if (throwable != null ) {
3938 logger .error ("completableFuture1 error:{}" , throwable );
4039 }
4140 });
4241
4342 CompletableFuture <String > completableFuture2 = CompletableFuture .supplyAsync (
44- () -> getResult ( word2 , 1500 ), executorService )
43+ () -> runTask ( "result2" , 1500 ), executorService )
4544 .whenComplete ((result , throwable ) ->{
4645 if (result != null ) {
47- strList .add (result );
46+ resultList .add (result );
4847 }
4948 if (throwable != null ) {
5049 logger .error ("completableFuture2 error:{}" , throwable );
@@ -57,27 +56,29 @@ public static void allOfGet() {
5756 futureList .add (completableFuture2 );
5857
5958 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 );
6765 }
68- List <String > resultList = new ArrayList <>(strList );
66+ List <String > list = new ArrayList <>(resultList );
6967
70- resultList .forEach (System .out ::println );
68+ list .forEach (System .out ::println );
7169 }
7270
7371
74- private static String getResult (String result , int millis ) {
72+ private static String runTask (String result , int millis ) {
7573 try {
74+ //此处忽略实际的逻辑,用sleep代替
7675 //任务耗时。可以分别设置1000和3000,看未超时和超时的不同结果。
7776 Thread .sleep (millis );
7877 } catch (InterruptedException e ) {
7978 logger .error ("supplyAsyncGet error." );
8079 }
8180 return result ;
8281 }
82+
83+
8384}
0 commit comments