Guava并发体验-2

时间:2019-02-20
本文章向大家介绍Guava并发体验-2,主要包括Guava并发体验-2使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
import com.google.common.util.concurrent.*;
import com.sun.corba.se.spi.ior.ObjectKey;

import java.util.concurrent.*;

/**
 * @Autohor MrZhong
 * @Description:
 **/
public class ThreadTest {

    private static int num = 0;

    private static StringBuilder builder = new StringBuilder();

    public static void main(String[] args) throws InterruptedException {
        //定义 future
        CompletableFuture<Integer> completableFuture ;

        for (int i = 1; i <=2 ; i++) {
            //lambda 表达式接收的参数必须是 final 类型
            int finalI = i;
            //supplyAsync可以支持返回值。runAsync方法不支持返回值。
            completableFuture = CompletableFuture.supplyAsync(()->{
                System.out.println("开始执行……");
                return finalI*1;
            });
            //当CompletableFuture的计算结果完成,或者抛出异常的时候,可以执行特定的Action。
            completableFuture.whenComplete((integer, throwable) -> {
                System.out.println("结果参数:"+integer);
                num+=integer;
                System.out.println("异常类型:"+throwable.toString());
            });
        }

        Thread.sleep(100);
        System.out.println("最终num值:"+num);
        }
}