|
| 1 | +package java0.conc0303.future; |
| 2 | + |
| 3 | +import java.util.concurrent.CompletableFuture; |
| 4 | + |
| 5 | +public class CompletableFutureDemo { |
| 6 | + |
| 7 | + public static void main(String[] args){ |
| 8 | + |
| 9 | + // 1.变换结果 |
| 10 | + System.out.println("=====>1.变换结果"); |
| 11 | + String result1 = CompletableFuture.supplyAsync(()->{return "Hello ";}).thenApplyAsync(v -> v + "world").join(); |
| 12 | + System.out.println(result1); |
| 13 | + |
| 14 | + // 2.消费 |
| 15 | + CompletableFuture.supplyAsync(()->{return "Hello ";}).thenAccept(v -> { System.out.println("=====>2.消费");System.out.println("consumer: " + v);}); |
| 16 | + |
| 17 | + // 3.组合 |
| 18 | + System.out.println("=====>3.组合"); |
| 19 | + String result3 = CompletableFuture.supplyAsync(()->{ |
| 20 | + try { |
| 21 | + Thread.sleep(1000); |
| 22 | + } catch (InterruptedException e) { |
| 23 | + e.printStackTrace(); |
| 24 | + } |
| 25 | + return "Hello"; |
| 26 | + }).thenCombine(CompletableFuture.supplyAsync(()->{ |
| 27 | + try { |
| 28 | + Thread.sleep(2000); |
| 29 | + } catch (InterruptedException e) { |
| 30 | + e.printStackTrace(); |
| 31 | + } |
| 32 | + return "world"; |
| 33 | + }),(s1,s2)->{return s1 + " " + s2;}).join(); |
| 34 | + System.out.println("thenCombine:"+result3); |
| 35 | + |
| 36 | + CompletableFuture.supplyAsync(() -> "Hello, java course.") |
| 37 | + .thenApply(String::toUpperCase).thenCompose(s -> CompletableFuture.supplyAsync(s::toLowerCase)).thenAccept(v -> { System.out.println("thenCompose:"+v);}); |
| 38 | + |
| 39 | + // 4.竞争 |
| 40 | + System.out.println("=====>4.竞争"); |
| 41 | + String result4 = CompletableFuture.supplyAsync(()->{ |
| 42 | + try { |
| 43 | + Thread.sleep(100); |
| 44 | + } catch (InterruptedException e) { |
| 45 | + e.printStackTrace(); |
| 46 | + } |
| 47 | + return "Hi Boy"; |
| 48 | + }).applyToEither(CompletableFuture.supplyAsync(()->{ |
| 49 | + try { |
| 50 | + Thread.sleep(300); |
| 51 | + } catch (InterruptedException e) { |
| 52 | + e.printStackTrace(); |
| 53 | + } |
| 54 | + return "Hi Girl"; |
| 55 | + }),(s)->{return s;}).join(); |
| 56 | + System.out.println(result4); |
| 57 | + |
| 58 | + // 5.补偿异常 |
| 59 | + System.out.println("=====>5.补偿异常"); |
| 60 | + String result5 = CompletableFuture.supplyAsync(()->{ |
| 61 | + try { |
| 62 | + Thread.sleep(100); |
| 63 | + } catch (InterruptedException e) { |
| 64 | + e.printStackTrace(); |
| 65 | + } |
| 66 | + if(true) { |
| 67 | + throw new RuntimeException("exception test!"); |
| 68 | + } |
| 69 | + |
| 70 | + return "Hi Boy"; |
| 71 | + }).exceptionally(e->{ |
| 72 | + System.out.println(e.getMessage()); |
| 73 | + return "Hello world!"; |
| 74 | + }).join(); |
| 75 | + System.out.println(result5); |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments