ThreadPool+CountDownLatch+Callable实现多线程编程

问题背景:

    在Java web项目中,Service层的实现类中需要一个方法连续调用多个别的APP的API,且请求结果之间互相不依赖。如果在项目中给每个方法内部都去新建指定数量的线程,则在高并发场景下由于线程创建的过多,会导致系统资源消耗过多,系统运行变慢或者宕机,所以需要使用线程池;每次api请求之后有返回结果,需要拿到返回结果,并感知可能发生的异常,因此要使用Callable接口实现线程;因为线程的执行是异步的,我们需要等待所有的线程都执行结束后才能在此service层的方法中返回处理结果,因为存在多线程线程等待的问题,也就是说,在调用api的线程没有全部执行完毕之前,父线程不能结束,否则结果不正确。所以我们要使用CountDownLatch。

代码编写:

import org.springframework.beans.factory.DisposableBean;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
@Service
public class ServiceImpl implements DisposableBean {
    private static final int ncpu = Runtime.getRuntime().availableProcessors();
    private static final BlockingQueue queue = new ArrayBlockingQueue(1000);
    private static final ThreadPoolExecutor poolExecutor =
            new ThreadPoolExecutor(ncpu,2*ncpu,1, TimeUnit.MINUTES,queue);
    public void test(int size) throws InterruptedException, ExecutionException {

        CountDownLatch latch = new CountDownLatch(size);
        List<Future> result = new ArrayList<>();
        for(int i=0;i<size;i++){
            Future<String> future =  poolExecutor.submit(()->{
                latch.countDown();
                return "hi";
            });
            result.add(future);
        }
        latch.await(10,TimeUnit.SECONDS);
        StringBuilder stringBuilder = new StringBuilder();
        for(Future future:result){

            stringBuilder.append(future.get());
        }
        System.out.println(stringBuilder.toString());
    }


    //关闭容器销毁该对象的时候,关闭线程池
    @Override
    public void destroy() throws Exception {
        poolExecutor.shutdownNow();
    }
}

说明:1.关于线程池的最大线程数:因为是调用远程API,IO是主要耗时的地方,所以任务算是IO密集型任务,因此最大线程数用      的2*NCPU;线程池的任务队列使用的是有界队列,且队列的容量也不大;

2.实现DisposableBean重写destroy方法,是为了在关闭容器的时候关闭线程池

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值