Java并发编程:线程池ThreadPoolExecutor的使用

package com.ctc.north.local.service.component.credit;

import com.ctc.north.local.api.model.uncomplex.response.VentureStopResponse;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.boot.autoconfigure.security.SecurityProperties;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author zhuxx
 * @desc 线程池测试
 **/
public class ExcutorsTest {
    public static void main(String[] args) {
        //待处理的数据集合List
        List<UserVo> userList = getUservoList();

        LinkedBlockingDeque blockingDeque = new LinkedBlockingDeque<Callable>(userList.size());
        //submit返回Future结果
        List<Future> futureList = new ArrayList<Future>();

        //CountDownLatch是一个同步计数器,能够保证在其他线程完成某一个业务操作前,当前线程一直处于等待/阻塞状态。
        //具体来说,这个计数器将会从给定的某一个数值count开始,通过countDown()方法的调用进行倒数。
        //当执行某一次countDown()操作后,计数器的count数值等于0,所有调用了await()方法的线程,就解除等待/阻塞状态继续执行
        CountDownLatch latch = new CountDownLatch(userList.size());
        //ThreadFactory就是一个线程工厂负责生产线程的
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("venture-stop-%d").build();
        //创建线程池
        ExecutorService cachedThreadPool = new ThreadPoolExecutor(3,
                6,
                0,
                TimeUnit.SECONDS,
                blockingDeque, threadFactory);
        //ExecutorCompletionService将BlockingQueue和Executor封装起来,然后使用ExecutorCompletionService.submit()方法提交任务。
        //<String>数据类型与Callable返回的数据类型一致;
        CompletionService<String> cs = new ExecutorCompletionService<String>(cachedThreadPool);

        userList.stream().forEach(userVo -> {
            //处理任务
            Callable<String> callable = () -> {
                latch.countDown();
                System.out.println("线程名称:"+Thread.currentThread().getName());
                System.out.println("线程返回值:"+userVo.id+"-1");
                return userVo.id+"-1";
            };
            futureList.add(cs.submit(callable));
        });

        try {
            //所有子线程执行完毕(计数器的count数值等于0),可以继续执行
            latch.await();
            System.out.println("执行结果:");
            futureList.stream().forEach(futrue ->{
                try {
                    //获取线程执行结果
                    System.out.println(futrue.get());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("==============================================");
    }

    public static List<UserVo> getUservoList(){
        List<UserVo> userList = new ArrayList<UserVo>();
        for(int i=0;i<6;i++){
            UserVo userVo = new UserVo();
            userVo.id=i+"00";
            userVo.name="AA"+i;
            userVo.age="2"+i;
            userList.add(userVo);
        }
        return userList;
    }
}
class UserVo{
  public String id;
  public String name;
  public String age;
}

执行结果如下: 

注意:

如果需要通过线程池执行任务,无需关注返回结果,即如下操作:

1、去掉CountDownLatch latch = new CountDownLatch(userList.size());

2、去掉latch.countDown();

3、去掉latch.await();

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值