package com.alatus.search; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CompletableFutureTest { public static ExecutorService service = Executors.newFixedThreadPool(10); public static void main(String[] args) throws InterruptedException, ExecutionException { CompletableFuture<String> img = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("查询商品的图片信息"); return "hello.jpg"; },service); CompletableFuture<String> attr = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("查询商品的图片属性"); return "黑色+256G"; },service); CompletableFuture<String> reduction = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("查询商品的介绍信息"); return "华为"; },service); // 全部执行完成的方式 CompletableFuture<Void> all = CompletableFuture.allOf(img, attr, reduction); // 任意执行完的方式 CompletableFuture<Object> any = CompletableFuture.anyOf(img, attr, reduction); System.out.println(any.get()); } }
package com.alatus.search; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CompletableFutureTest { public static ExecutorService service = Executors.newFixedThreadPool(10); public static void main(String[] args) throws InterruptedException, ExecutionException { CompletableFuture<String> img = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("查询商品的图片信息"); return "hello.jpg"; },service); CompletableFuture<String> attr = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(3000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("查询商品的图片属性"); return "黑色+256G"; },service); CompletableFuture<String> reduction = CompletableFuture.supplyAsync(() -> { try { Thread.sleep(2000); } catch (InterruptedException e) { throw new RuntimeException(e); } System.out.println("查询商品的介绍信息"); return "华为"; },service); // 全部执行完成的方式 CompletableFuture<Void> all = CompletableFuture.allOf(img, attr, reduction); // 任意执行完的方式 CompletableFuture<Object> any = CompletableFuture.anyOf(img, attr, reduction); System.out.println(any.get()); } }
08-11
482
06-11
1002
09-03
1461
10-31
1489
08-24
3183