一、在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接口的任务类