关于线程池的调用 之 自定义线程池


## **关于线程池的调用(自定义线程池)**

  ThreadPoolExecutor threadPoolExecutor = ThreadUtil.newExecutor(3, 1000);
	初始线程数为corePoolSize  指定的大小   : 3 
	最大线程数限制  指定的大小   : 1000 
	默认使用LinkedBlockingQueue,默认队列大小为1024(最大等待数1024)
	
	当运行线程大于corePoolSize放入队列,队列满后抛出异常

	推荐  以后 使用 ExecutorBuilder 
	ThreadPoolExecutor threadPoolExecutor1 = ExecutorBuilder.create()
				//初始线程数   2
                .setCorePoolSize(2)	
                 // 最大线程数  20
                .setMaxPoolSize(20) 
                 //指定线程等待队列长度  默认1024超过抛出异常
                .setWorkQueue(new LinkedBlockingQueue<>(100)).build();  
/****************************************/
	**测速代码如下**
	public static void main(String[] args) {
        List<Integer> numList = new ArrayList<>();
        for (int i = 0; i < 1000; i++) {
            numList.add(i);
        }
        AtomicInteger atomicInteger = new AtomicInteger();
    
        ThreadPoolExecutor threadPoolExecutor1 = ExecutorBuilder.create()
                .setCorePoolSize(2)
                .setMaxPoolSize(20)
                .setWorkQueue(new LinkedBlockingQueue<>(numList.size())).build();
        for (int i = 0; i < numList.size(); i++) {
            int finalI = i;
            threadPoolExecutor1.submit(() -> {

                atomicInteger.getAndIncrement();
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                show(numList.get(finalI));
                System.out.println("atomicInteger  统计"+Thread.currentThread().getName() +
                "当前执行进度 " + atomicInteger + "/" + numList.size());
            });

        }

		//如果需要返回值或者返回请求啥的 就添加下面得代码;

        threadPoolExecutor.shutdown();
        try {
            //当线程池中的线程阻塞1分钟后进入shutdownNow()方法中关闭线程
            if (!threadPoolExecutor.awaitTermination(5, TimeUnit.MINUTES)) {
                threadPoolExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            threadPoolExecutor.shutdownNow();
        }

        System.out.println("完成");
    }

    public static void show(Integer num){
        System.out.println("第"+num+"只猫");
    }



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值