java学习笔记---多线程的实现2------CompletableFuture

多线程实现方式1:https://blog.csdn.net/qq_39849328/article/details/103303432

多线程之通过completableFuture实现多线程:

import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.junit.Test;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;

public class CompletableFutureStudyFun1 {
    private volatile Integer baseNum = 1;
    AtomicInteger counter = new AtomicInteger(0);

    @Test
    public void executorServiceTestService() {
        List<CompletableFuture<Integer>> futureList = Lists.newArrayList();

        //创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor( 3, 4, 60L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(1024), new ThreadFactoryBuilder().setNameFormat("service_test").build(), new ThreadPoolExecutor.AbortPolicy());
        //通过completableFuture,循环调用资源。
        for (int i = 0; i<10; i++) {
            final int per = i==0 ? 1 : i;
            CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> getSumForParam(per), threadPoolExecutor);
            //无需等待结果,主线程继续执行。
            futureList.add(future);
        }

        //获得返回结果
        List<Integer> futureCallBack = Lists.newArrayList();

        futureList.stream().forEach(future -> {
            try {
                //获得线程返回值。
                int res = future.exceptionally(e -> { return null;}).get(60, TimeUnit.SECONDS);
                //添加到线程结果列表
                futureCallBack.add(res);
                System.out.println("=======>>>>>>>>>>>>>>"+res);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        });
        //循环打印
        futureCallBack.stream().forEach(System.out::println);
        //用于debug查看各个参数值,判断实现情况
        System.out.println("================");
    }

    /**
     * @description 多线程执行方法。
     * @param per
     * @return
     * @eg synchronized保证参数有序性,并且尝试使用cas
     */
    public /*synchronized*/ int getSumForParam(int per) {
        
        //System.out.print( counter.incrementAndGet() + " ");
        return baseNum++;
    }

}

作者原创:仅用于学习分享和记录,请求转载。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值