Skip to content

Instantly share code, notes, and snippets.

@sdhjl2000
Created September 19, 2018 00:05
Show Gist options
  • Save sdhjl2000/f35490d73fdf0e3519bf34523a33562d to your computer and use it in GitHub Desktop.
Save sdhjl2000/f35490d73fdf0e3519bf34523a33562d to your computer and use it in GitHub Desktop.
CompletableFuture
public class CompletableFutureParallel {
private static final int CORE_POOL_SIZE = 4;
private static final int MAX_POOL_SIZE = 12;
private static final long KEEP_ALIVE_TIME = 5 L;
private final static int QUEUE_SIZE = 1600;
protected final static ExecutorService THREAD_POOL = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new LinkedBlockingQueue < > (QUEUE_SIZE));
public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
OrderInfo orderInfo = new OrderInfo(); //CompletableFuture 的List
List < CompletableFuture > futures = new ArrayList < > ();
futures.add(CompletableFuture.runAsync(() - > {
System.out.println("当前任务Customer,线程名字为:" + Thread.currentThread().getName());orderInfo.setCustomerInfo(new CustomerInfo());
}, THREAD_POOL));
futures.add(CompletableFuture.runAsync(() - > {
System.out.println("当前任务Discount,线程名字为:" + Thread.currentThread().getName());orderInfo.setDiscountInfo(new DiscountInfo());
}, THREAD_POOL));
futures.add(CompletableFuture.runAsync(() - > {
System.out.println("当前任务Food,线程名字为:" + Thread.currentThread().getName());orderInfo.setFoodListInfo(new FoodListInfo());
}, THREAD_POOL));
futures.add(CompletableFuture.runAsync(() - > {
System.out.println("当前任务Other,线程名字为:" + Thread.currentThread().getName());orderInfo.setOtherInfo(new OtherInfo());
}, THREAD_POOL));
CompletableFuture allDoneFuture = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]));
allDoneFuture.get(10, TimeUnit.SECONDS);
System.out.println(orderInfo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment