@@ -8,50 +8,31 @@ public class isCompletedExceptionallyAndIsCancelledExample {
8
8
9
9
public static void main (String [] args ) throws InterruptedException , ExecutionException , TimeoutException {
10
10
11
- CompletableFuture <Integer > cf1 = CompletableFuture .supplyAsync (() -> {
12
- sleep (1000 );
13
- return 10 ;
14
- });
15
-
11
+ CompletableFuture <Integer > cf1 = CompletableFuture .supplyAsync (() -> 10 );
16
12
CompletableFuture <Integer > cf2 = CompletableFuture .supplyAsync (() -> {
17
- sleep (2000 );
18
- return 10 ;
19
- // throw new RuntimeException("두 번째 작업에서 예외 발생");
20
- });
21
-
22
- CompletableFuture <Integer > cf3 = CompletableFuture .supplyAsync (() -> {
23
- sleep (1000 );
24
13
return 20 ;
14
+ // throw new RuntimeException("error");
25
15
});
26
16
27
17
// cf2.cancel(true);
28
18
29
- CompletableFuture <Integer > combinedFuture = cf1 .thenCombine (cf2 .exceptionally (e -> 15 ), (result1 , result2 ) -> {
19
+ CompletableFuture <Integer > combinedFuture =
20
+ cf1 .thenCombine (cf2 .exceptionally (e -> 15 ), (result1 , result2 ) -> {
30
21
31
- if (cf2 .isCancelled ()) { // isDone() 과 구분할 수 있다
32
- return 0 ;
22
+ if (cf2 .isCancelled ()) {
23
+ return 0 ; // 취소 완료
24
+ }
25
+ else if (cf2 .isCompletedExceptionally ()) {
26
+ return result2 ; // 예외 완료
27
+ }
28
+ else if (cf2 .isDone ()) {
29
+ return result1 + result2 ; // 정상 완료
30
+ }
31
+ else return -1 ;
33
32
34
- } else if (cf2 .isCompletedExceptionally ()) { // isDone() 과 구분할 수 있다
35
- return result2 ;
36
-
37
- } else if (cf2 .isDone ()){
38
- return result1 + result2 ;
39
- } else {
40
-
41
- return -1 ;
42
- }
43
- })
44
- .thenCombine (cf3 , (result2 , result3 ) -> result2 + result3 );
33
+ });
45
34
46
35
int result = combinedFuture .join (); // 결과 가져오기
47
36
System .out .println ("최종 결과: " + result );
48
37
}
49
-
50
- private static void sleep (int milliseconds ) {
51
- try {
52
- Thread .sleep (milliseconds );
53
- } catch (InterruptedException e ) {
54
- Thread .currentThread ().interrupt ();
55
- }
56
- }
57
- }
38
+ }
0 commit comments