Java8新特性学习笔记-CompletableFuture

目录

代码

package test;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CompletableFutureTest {

	private static ExecutorService executorService = Executors.newFixedThreadPool(8);

	public static void main(String[] args) throws InterruptedException {

		// 创建异步执行任务:
		CompletableFuture<Double> completedFuture = CompletableFuture.supplyAsync(() -> {

			System.out.println("start");

			try {
				Thread.sleep(1000);
			} catch (InterruptedException ignored) {
			}
			if (Math.random() < 0.3) {
				throw new RuntimeException("fetch price failed!");
			}

			return 5 + Math.random() * 20;
		}, executorService);

		// 如果执行成功:
		completedFuture.thenAccept((result) -> {
			System.out.println("price: " + result);
		});

		// 如果执行异常:
		completedFuture.exceptionally((e) -> {
			e.printStackTrace();
			return null;
		});

		Thread.currentThread().join();
	}
}
上一篇:CompletableFuture方法总结


下一篇:J2SE I一一JDK9新特性(详解)