11package com .java8 .completefuture ;
22
3- import org .apache .log4j .LogManager ;
4- import org .apache .log4j .Logger ;
3+ import lombok .extern .slf4j .Slf4j ;
54
65import java .util .ArrayList ;
76import java .util .Collections ;
87import java .util .List ;
98import java .util .concurrent .*;
109
10+ @ Slf4j
1111public class WhenCompleteDemo {
1212
1313
14- private static Logger logger = LogManager .getLogger (WhenCompleteDemo .class );
1514
1615 public static void main (String [] args ) {
1716 whenComplete ();
@@ -28,15 +27,15 @@ public static void whenComplete() {
2827 () -> getResult (word1 , 1000 ), executorService )
2928 .whenComplete ((result , throwable ) ->{
3029 if (throwable != null ) {
31- logger .error ("completableFuture1 error:{} " , throwable );
30+ log .error ("completableFuture1 error:" , throwable );
3231 }
3332 });
3433
3534 CompletableFuture <String > completableFuture2 = CompletableFuture .supplyAsync (
3635 () -> getResult (word2 , 1500 ), executorService )
3736 .whenComplete ((result , throwable ) ->{
3837 if (throwable != null ) {
39- logger .error ("completableFuture2 error:{} " , throwable );
38+ log .error ("completableFuture2 error:" , throwable );
4039 }
4140 });
4241
@@ -63,7 +62,7 @@ private static String getResult(String result, int millis) {
6362 //任务耗时。可以分别设置1000和3000,看未超时和超时的不同结果。
6463 Thread .sleep (millis );
6564 } catch (InterruptedException e ) {
66- logger .error ("supplyAsyncGet error." );
65+ log .error ("supplyAsyncGet error." );
6766 }
6867 return result ;
6968 }
@@ -74,11 +73,11 @@ private static String getFutureResult(CompletableFuture<String> completableFutur
7473 //获取返回值,2秒超时
7574 result = completableFuture .get (timeout , TimeUnit .SECONDS );
7675 } catch (InterruptedException e ) {
77- logger .error ("InterruptedException error." , e );
76+ log .error ("InterruptedException error." , e );
7877 } catch (ExecutionException e ) {
79- logger .error ("ExecutionException error." , e );
78+ log .error ("ExecutionException error." , e );
8079 } catch (TimeoutException e ) {
81- logger .error ("TimeoutException error." , e );
80+ log .error ("TimeoutException error." , e );
8281 }
8382 return result ;
8483 }
0 commit comments