线程池ThreadPoolExecutor实际使用和介绍

  • Post author:
  • Post category:其他


今天小G,在开发一个项目的时候,导入excel,20万数据到数据库,该数据为业务数据

,无法让DBA进行导入,然后小G就想,那就线程走起;

说起线程就想起线程池,大家也知道,线程池可以防止

1、创建同类的线程导致消耗完内存

2、创建线程和销毁过度切换问题

那目前四种线程(小G也是网上查询下资料,因为也好久不用)

线程 优点
newCachedThreadPool 无需考虑线程长度,空闲可以回收,无空闲新增,新增无极限
newFixedThreadPool 需要赋值线程数量,可以控制并发数,超过可以在队列
newScheduledThreadPool 可以延迟执行线程,应该是任务用这个执行
newSingleThreadExecutor 看名就是单例,有顺序的执行制定的FIFO,LIFO

根据需求使用的是newFixedThreadPool,为什么这样考虑,这个线程周期可能比较长,最喜欢里面的QUEUE队列,设置完线程数,超过的可以在队列过程中等待,小G感觉如果使用newCachedThreadPool ,无法控制线程数量,应该是周期比较小(线程执行时间段),并发量不大,才使用,因为他会无限制开线程

1、ThreadPoolExecutor

  
public class ThreadUtil{
    /**
     * 线程数
     */
    private static final int CORE_SIZE = 10;
    /**
     最大值
     */
    private static final int MAX_SIZE = 20;
    /**
     *  线程空闲多久进行回收
     */
    private static final long KEEP_ALIVE_TIME = 60;
    /**
     * 阻塞队列的大小
     *
     */
    private static final int QUEUE_SIZE = 2000;

    /**
     * 使用多少的队列
     */
    private static  int USER_QUEUE_SIZE=0;

    /**
     * 使用多少的队列
     * @return
     */
    public static int getUserQueueSize() {
        return USER_QUEUE_SIZE;
    }
    private static ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, KEEP_ALIVE_TIME,
            TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadPoolExecutor.AbortPolicy());


    public static ThreadPoolExecutor getThreadPool() {
        if(threadPool==null){
            new ThreadPoolExecutor(CORE_SIZE, MAX_SIZE, KEEP_ALIVE_TIME,
                    TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(QUEUE_SIZE), new ThreadPoolExecutor.AbortPolicy());

        }
        USER_QUEUE_SIZE = threadPool.getQueue().size();
        return threadPool;
    }

}


2、Thread代码

ThreadPoolExecutorUtil.getThreadPool().excel(new Thread1 ());

3、里面new runnabel写个类就可以

  public    class   Thread1 implements Runnable, Serializable{
        @Override
        public void run() {
        }
    }

小结:如果大家赶紧,怕业务上去无法控制,可以多设置下QUEUE的队列数,然后在使用过程中,自己自定义一个值,先跟自己设计的值比较,这样后续如果量比较大也好控制,后续我会把如何处理大量数据通过excel导入数据可以,通过线程哈,写的不好小G让大家见笑

后续:为什么建议大家实验ThreaPoolExecutor 而不适用executors方法:

  1. FixedThreadPool 和 SingleThreadExecutor : 允许请求的队列长度为

    Integer.MAX_VALUE,可能堆积大量的请求,从而导致 OOM。
  2. CachedThreadPool 和 ScheduledThreadPool : 允许创建的线程数量为

    Integer.MAX_VALUE ,可能会创建大量线程,从而导致 OOM。


另外,大家可以使用cpu来决定线程数

下面为获取cpu的数量


    /**
     * 根据cpu的数量动态的配置核心线程数和最大线程数
     */
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

其中 ,其中可以有优化:最大优化为CPU_COUNT * 2 + 1,最多优化为 CPU_COUNT * 2 + 1;(队列满的时候开启该配置线程数量)



版权声明:本文为a372663325原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。