|
| 1 | +package com.yale.test.thread.heima.zhangxiaoxiang; |
| 2 | + |
| 3 | +import java.lang.management.ManagementFactory; |
| 4 | +import java.lang.management.MemoryMXBean; |
| 5 | +import java.lang.management.ThreadMXBean; |
| 6 | +import java.util.Random; |
| 7 | +import java.util.concurrent.Callable; |
| 8 | +import java.util.concurrent.CompletableFuture; |
| 9 | +import java.util.concurrent.CompletionService; |
| 10 | +import java.util.concurrent.ExecutionException; |
| 11 | +import java.util.concurrent.ExecutorCompletionService; |
| 12 | +import java.util.concurrent.ExecutorService; |
| 13 | +import java.util.concurrent.Executors; |
| 14 | +import java.util.concurrent.Future; |
| 15 | +import java.util.concurrent.TimeoutException; |
| 16 | + |
| 17 | +/* |
| 18 | + * 使用CompletableFuture |
| 19 | + * 使用Future获得异步执行结果时,要么调用阻塞方法get(),要么轮询看isDone()是否为true,这两种方法都不是很好,因为主线程也会被迫等待。 |
| 20 | + * 从Java 8开始引入了CompletableFuture,它针对Future做了改进,可以传入回调对象,当异步任务完成或者发生异常时,自动调用回调对象的回调方法。 |
| 21 | + * 我们以获取股票价格为例,看看如何使用CompletableFuture: |
| 22 | + * 小结 |
| 23 | + CompletableFuture可以指定异步处理流程: |
| 24 | + thenAccept()处理正常结果; |
| 25 | + exceptional()处理异常结果; |
| 26 | + thenApplyAsync()用于串行化另一个CompletableFuture; |
| 27 | + anyOf()和allOf()用于并行化多个CompletableFuture。 |
| 28 | + */ |
| 29 | +public class CompletableFutureDemo { |
| 30 | + public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException { |
| 31 | + /* |
| 32 | + * 创建异步执行任务 |
| 33 | + * 创建一个CompletableFuture是通过CompletableFuture.supplyAsync()实现的,它需要一个实现了Supplier接口的对象: |
| 34 | + * public interface Supplier<T> { |
| 35 | + T get(); |
| 36 | + } |
| 37 | + * 这里我们用lambda语法简化了一下,直接传入CompletableFutureDemo::fetchPrice,因为CompletableFutureDemo.fetchPrice()静态方法的签名符合Supplier接口的定义(除了方法名外)。 |
| 38 | + * 紧接着,CompletableFuture已经被提交给默认的线程池执行了,我们需要定义的是CompletableFuture完成时和异常时需要回调的实例。完成时,CompletableFuture会调用Consumer对象: |
| 39 | + * public interface Consumer<T> { |
| 40 | + void accept(T t); |
| 41 | + } |
| 42 | + * 异常时,CompletableFuture会调用Function对象: |
| 43 | + * public interface Function<T, R> { |
| 44 | + R apply(T t); |
| 45 | + } |
| 46 | + * 这里我们都用lambda语法简化了代码。 |
| 47 | + * 可见CompletableFuture的优点是: |
| 48 | + 异步任务结束时,会自动回调某个对象的方法; |
| 49 | + 异步任务出错时,会自动回调某个对象的方法; |
| 50 | + 主线程设置好回调后,不再关心异步任务的执行。 |
| 51 | + * |
| 52 | + */ |
| 53 | + CompletableFuture<Double> cf = CompletableFuture.supplyAsync(CompletableFutureDemo::fetchPrice);//supplyAsync内部会启动线程 |
| 54 | + |
| 55 | + cf.thenAccept((result)->{//如果执行成功 |
| 56 | + System.out.println("price:" + result); |
| 57 | + }); |
| 58 | + |
| 59 | + cf.exceptionally((e) -> {//如果执行异常 |
| 60 | + e.printStackTrace(); |
| 61 | + return null; |
| 62 | + }); |
| 63 | + |
| 64 | + //主线程不要立刻结束,否则CompletableFuture默认使用的线程池会立刻关闭; |
| 65 | + Thread.sleep(200); |
| 66 | + |
| 67 | + |
| 68 | + /* |
| 69 | + * 如果只是实现了异步回调机制,我们还看不出CompletableFuture相比Future的优势。CompletableFuture更强大的功能是,多个CompletableFuture可以串行执行, |
| 70 | + * 例如,定义两个CompletableFuture,第一个CompletableFuture根据证券名称查询证券代码,第二个CompletableFuture根据证券代码查询证券价格,这两个CompletableFuture实现串行操作如下: |
| 71 | + */ |
| 72 | + CompletableFuture<String> cfQuery = CompletableFuture.supplyAsync(()->{//第一个任务 |
| 73 | + return queryCode("中国石油"); |
| 74 | + }); |
| 75 | + |
| 76 | + CompletableFuture<Double> cfFetch = cfQuery.thenApplyAsync((code)->{//cfQuery成功后继续执行下一个任务 |
| 77 | + return fetchPrice(code); |
| 78 | + }); |
| 79 | + |
| 80 | + cfFetch.thenAccept((result)->{//cfFetch成功后打印结果: |
| 81 | + System.out.println("price:" + result); |
| 82 | + }); |
| 83 | + //主线程不要立刻结束,否则CompletableFuture默认使用的线程池会立刻关闭 |
| 84 | + Thread.sleep(2000); |
| 85 | + |
| 86 | + /* |
| 87 | + * 除了串行执行外,多个CompletableFuture还可以并行执行。例如,我们考虑这样的场景: |
| 88 | + * 同时从新浪和网易查询证券代码,只要任意一个返回结果,就进行下一步查询价格,查询价格也同时从新浪和网易查询,只要任意一个返回结果,就完成操作: |
| 89 | + * 下面逻辑实现的异步查询规则实际上是: |
| 90 | + ┌─────────────┐ ┌─────────────┐ |
| 91 | + │ Query Code │ │ Query Code │ |
| 92 | + │ from sina │ │ from 163 │ |
| 93 | + └─────────────┘ └─────────────┘ |
| 94 | + │ │ |
| 95 | + └───────┬───────┘ |
| 96 | + ▼ |
| 97 | + ┌─────────────┐ |
| 98 | + │ anyOf │ |
| 99 | + └─────────────┘ |
| 100 | + │ |
| 101 | + ┌───────┴────────┐ |
| 102 | + ▼ ▼ |
| 103 | + ┌─────────────┐ ┌─────────────┐ |
| 104 | + │ Query Price │ │ Query Price │ |
| 105 | + │ from sina │ │ from 163 │ |
| 106 | + └─────────────┘ └─────────────┘ |
| 107 | + │ │ |
| 108 | + └────────┬───────┘ |
| 109 | + ▼ |
| 110 | + ┌─────────────┐ |
| 111 | + │ anyOf │ |
| 112 | + └─────────────┘ |
| 113 | + │ |
| 114 | + ▼ |
| 115 | + ┌─────────────┐ |
| 116 | + │Display Price│ |
| 117 | + └─────────────┘ |
| 118 | + * 除了anyOf()可以实现“任意个CompletableFuture只要一个成功”,allOf()可以实现“所有CompletableFuture都必须成功”,这些组合操作可以实现非常复杂的异步流程控制。 |
| 119 | + * 最后我们注意CompletableFuture的命名规则: |
| 120 | + * xxx():表示该方法将继续在已有的线程中执行; |
| 121 | + * xxxAsync():表示将异步在线程池中执行。 |
| 122 | + * CompletableFuture可以指定异步处理流程: |
| 123 | + * thenAccept()处理正常结果; |
| 124 | + * exceptional()处理异常结果; |
| 125 | + * thenApplyAsync()用于串行化另一个CompletableFuture; |
| 126 | + * anyOf()和allOf()用于并行化多个CompletableFuture。 |
| 127 | + */ |
| 128 | + CompletableFuture<String> cfQueryFromSina = CompletableFuture.supplyAsync(()->{//俩个CompletableFuture执行异步查询 |
| 129 | + return queryCode("中国石油", "https://finace.sina.com.cn/code/"); |
| 130 | + }); |
| 131 | + |
| 132 | + CompletableFuture<String> cfQueryForm163 = CompletableFuture.supplyAsync(()->{ |
| 133 | + return queryCode("中国石油", "https://money.163.com/code/"); |
| 134 | + }); |
| 135 | + |
| 136 | + //用anyof合并为一个新的CompletableFuture: |
| 137 | + CompletableFuture<Object> cfQueryMegre = CompletableFuture.anyOf(cfQueryFromSina, cfQueryForm163); |
| 138 | + |
| 139 | + CompletableFuture<Double> cfFetchFromSina = cfQueryMegre.thenApplyAsync((code)->{//俩个CompletableFuture执行异步查询 |
| 140 | + return fetchPrice((String)code, "https://finance.sina.com.cn/price/"); |
| 141 | + }); |
| 142 | + |
| 143 | + CompletableFuture<Double> cfFetchFrom163 = cfQueryMegre.thenApplyAsync((code)->{ |
| 144 | + return fetchPrice((String)code, "https://money.163.com/price"); |
| 145 | + }); |
| 146 | + |
| 147 | + //用anyof合并为一个新的CompletableFuture: |
| 148 | + CompletableFuture<Object> cfFetchSec = CompletableFuture.anyOf(cfFetchFromSina, cfFetchFrom163); |
| 149 | + cfFetchSec.thenAccept((result)->{//最终结果 |
| 150 | + System.out.println("price:" + result); |
| 151 | + }); |
| 152 | + //主线程不要立刻结束,否则CompletableFuture默认使用的线程池会立刻关闭 |
| 153 | + Thread.sleep(2000); |
| 154 | + |
| 155 | + /** |
| 156 | + * 咨询一下老师。我看到supplyAsync在thenAccept的前面,而且任务是在supplyAsync中启动的。那有没有可能在通过cf.thenAccept设置回调前, |
| 157 | + * 异步执行的任务已经完成了(假如fetchPrice是个空函数),这样在thenAccept中设置的回调就不会被执行了,有这种可能吗? |
| 158 | + * 答案是:可以执行 |
| 159 | + */ |
| 160 | + // 创建异步执行任务: |
| 161 | + CompletableFuture<Double> cfTime = CompletableFuture.supplyAsync(CompletableFutureDemo::fetchPriceZer); |
| 162 | + // 暂停让Future完成: |
| 163 | + Thread.sleep(5000); |
| 164 | + // 如果执行成功: |
| 165 | + cfTime.thenAccept((result) -> { |
| 166 | + System.out.println("thenAccept: " + result); |
| 167 | + }); |
| 168 | + // 如果执行异常: |
| 169 | + cfTime.exceptionally((e) -> { |
| 170 | + e.printStackTrace(); |
| 171 | + return null; |
| 172 | + }); |
| 173 | + // 主线程不要立刻结束,否则CompletableFuture默认使用的线程池会立刻关闭: |
| 174 | + Thread.sleep(2000); |
| 175 | + } |
| 176 | + |
| 177 | + static Double fetchPriceZer() { |
| 178 | + System.out.println("fetched!"); |
| 179 | + return 123.46; |
| 180 | + } |
| 181 | + |
| 182 | + static Double fetchPrice() { |
| 183 | + try { |
| 184 | + Thread.sleep(100); |
| 185 | + } catch (InterruptedException e) { |
| 186 | + e.printStackTrace(); |
| 187 | + } |
| 188 | + if (Math.random() < 0.3) { |
| 189 | + throw new RuntimeException("fetch price failed"); |
| 190 | + } |
| 191 | + return 5 + Math.random() * 20; |
| 192 | + } |
| 193 | + |
| 194 | + static String queryCode(String name) { |
| 195 | + try { |
| 196 | + Thread.sleep(100); |
| 197 | + } catch (InterruptedException e) { |
| 198 | + e.printStackTrace(); |
| 199 | + } |
| 200 | + return "601857"; |
| 201 | + } |
| 202 | + |
| 203 | + static Double fetchPrice(String code) { |
| 204 | + try { |
| 205 | + Thread.sleep(100); |
| 206 | + } catch (InterruptedException e) { |
| 207 | + e.printStackTrace(); |
| 208 | + } |
| 209 | + return 5 + Math.random() * 20; |
| 210 | + } |
| 211 | + |
| 212 | + static String queryCode(String name, String url) { |
| 213 | + System.out.println("query Code " + name + " from " + url + "....."); |
| 214 | + try { |
| 215 | + Thread.sleep((long)(Math.random() * 100)); |
| 216 | + } catch (InterruptedException e) { |
| 217 | + e.printStackTrace(); |
| 218 | + } |
| 219 | + return "601857"; |
| 220 | + } |
| 221 | + |
| 222 | + static Double fetchPrice(String code, String url) { |
| 223 | + System.out.println("query price" + code + " from " + url); |
| 224 | + try { |
| 225 | + Thread.sleep((long)(Math.random() * 100)); |
| 226 | + } catch (InterruptedException e) { |
| 227 | + e.printStackTrace(); |
| 228 | + } |
| 229 | + return 5 + Math.random() * 20; |
| 230 | + } |
| 231 | +} |
0 commit comments