我是徐大志

有志者事竟成,破釜沉舟,百二秦关终属楚;
苦心人天不负,卧薪尝胆,两千越甲可吞吴。

java线程池的使用

一、在java中使用线程池的情况:

  1、任务执行时间比较长的时候,前台只需要在执行就可以,不需阻塞等待结果

  2、出现高并发的情况,如果没有线程池的管理,会撑爆内存,需要任务排队执行任务

二、线程池的使用:

  1、新城池的分类大类有四种,单例,可变,定长,缓存

  2、常用的情况就是热内比较多,而且任务的执行时间比较长的情况,需要排队执行任务,并且核心线程数量一定,排队线程不做限制

  

import org.springframework.beans.factory.annotation.Value;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadPoolManage {

    @Value("corePoolSize")
    private static int corePoolSize; //核心线程池数量(运行的最少线程)
    @Value("maxPoolSize")
    private static int maxPoolSize; //最大线程池数量(运行的最大线程)和队列容量无关

    private ThreadPoolManage (){}

    //单例线程池
    private static final ExecutorService fixedThreadPool = new ThreadPoolExecutor(
            corePoolSize,
            maxPoolSize,
            0L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue() //新建一个阻塞队列,任务入队等待
    );

    public static ExecutorService getFixedThreadPool() {
        return fixedThreadPool;
    }
}

三、线程池的使用:

  

ExecutorService fixedThreadPool = ThreadPoolManager.getFiedThreadPool();
                fixedThreadPool.execute(
                        new ReportTask(reportTaskParam,collectionLogService,collectionInfoService,
                                verifyService,odsInboundService));//自定义的实现Runnable接口的任务类

 

posted @ 2018-04-09 15:51  我是徐大志  阅读(151)  评论(0编辑  收藏  举报
【少年,我看你目光炯炯有神,将来一定能成大事!】