自定义线程池和合理配置线程数

不要用Excutors定义线程池,用ThreadPoolExcutor自定义

public class ExcutorDemo {

    public static void main(String[] args) {

        //ExecutorService threadPool = Executors.newFixedThreadPool(20);//一池20个线程
        //ExecutorService threadPool = Executors.newSingleThreadExecutor();//一池一个线程
        //ExecutorService threadPool = Executors.newCachedThreadPool();//一池n个线程
        //自定义线程池
        ExecutorService threadPool = new ThreadPoolExecutor(
                2,
                10,
                100L,
                 TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(4),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());



        try {
            for (int i = 0; i < 30; i++) {
                threadPool.execute(() -> {
                    System.out.println("线程开启 "+Thread.currentThread().getName());
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            threadPool.shutdown();
        }

    }
}

 

合理配置线程:

1.CPU密集型:高并发,任务执行时间短,一直告诉运行,线程池线程数一般设为cpu核数+1

2.IO密集型:a.IO密集型任务需要大量的IO,即大量的阻塞,尽可能配置多的线程数,如CPU核数*2+1

                     b.参考公式:CPU核数/(1-阻塞系数)    阻塞系数在0.8~0.9之间

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值