赞
踩
- public Map<String, String> test() throws InterruptedException, ExecutionException {
- // 不存在并发插入情况,不需要使用ConcurrentHashMap
- // Map<String, String> data = new ConcurrentHashMap<>(3);
- Map<String, String> data = new HashMap<>(3);
- //第一个任务。返回参数类型可自定义
- CompletableFuture<String> task01 = CompletableFuture.supplyAsync(() -> {
- try {
- TimeUnit.SECONDS.sleep(3);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return "task01";
- });
- //第二个任务。返回参数类型可自定义
- CompletableFuture<String> task02 = CompletableFuture.supplyAsync(() -> {
- try {
- TimeUnit.SECONDS.sleep(5);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return "task02";
- });
- // 第三个任务。返回参数类型可自定义
- CompletableFuture<String> task03 = CompletableFuture.supplyAsync(() -> {
- try {
- TimeUnit.SECONDS.sleep(3);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return "task03";
- });
- // get()方法会阻塞,最终得到处理时间,取决于多线程的最大响应时间的接口
- String task01Result = task01.get() ;
- String task02Result = task02.get() ;
- String task03Result = task03.get() ;
- data.put("task01", task01Result );
- data.put("task02", task02Result );
- data.put("task03", task03Result );
- return data;
- }
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。