1、线程池的建立 数组
咱们能够经过ThreadPoolExecutor来建立一个线程池。 缓存
建立一个线程池须要输入几个参数: spa
2、Executors提供了一些方便建立ThreadPoolExecutor的经常使用方法,主要有如下几个: 线程
一、 Executors.newFixedThreadPool(int nThreads);建立固定大小(nThreads,大小不能超过int的最大值)的线程池 rest
// 线程数量 日志
int nThreads = 20; 对象
// 建立executor 服务 排序
ExecutorService executor = Executors.newFixedThreadPool(nThreads) ; 接口
重载后的版本,须要多传入实现了ThreadFactory接口的对象。 队列
ExecutorService executor = Executors. newFixedThreadPool(nThreads, threadFactory);
说明:建立固定大小(nThreads,大小不能超过int的最大值)的线程池,缓冲任务的队列为LinkedBlockingQueue,大小为整型的 最大数,当使用此线程池时,在同执行的任务数量超过传入的线程池大小值后,将会放入LinkedBlockingQueue,在 LinkedBlockingQueue中的任务须要等待线程空闲后再执行,若是放入LinkedBlockingQueue中的任务超过整型的最大数 时,抛出RejectedExecutionException。
二、Executors.newSingleThreadExecutor():建立大小为1的固定线程池。
ExecutorService executor = Executors.newSingleThreadExecutor();
重载后的版本,须要多传入实现了ThreadFactory接口的对象。
ExecutorService executor = Executors. newSingleThreadScheduledExecutor(ThreadFactory threadFactory)
说明:建立大小为1的固定线程池,同时执行任务(task)的只有一个,其它的(任务)task都放在LinkedBlockingQueue中排队等待执行。
三、Executors.newCachedThreadPool();建立corePoolSize为0,最大线程数为整型的最大数,线程 keepAliveTime为1分钟,缓存任务的队列为SynchronousQueue的线程池。
ExecutorService executor = Executors.newCachedThreadPool();
固然也能够如下面的方式建立,重载后的版本,须要多传入实现了ThreadFactory接口的对象。
ExecutorService executor = Executors.newCachedThreadPool(ThreadFactory threadFactory) ;
说明:使用时,放入线程池的task任务会复用线程或启动新线程来执行,注意事项:启动的线程数若是超过整型最大值后会抛出RejectedExecutionException异常,启动后的线程存活时间为一分钟。
四、Executors.newScheduledThreadPool(int corePoolSize):建立corePoolSize大小的线程池。
//线程数量
int corePoolSize= 20;
// 建立executor 服务
ExecutorService executor = Executors.newScheduledThreadPool(corePoolSize) ;
重载后的版本,须要多传入实现了ThreadFactory接口的对象。
ExecutorService executor = Executors.newScheduledThreadPool(corePoolSize, threadFactory) ;
说明:线程keepAliveTime为0,缓存任务的队列为DelayedWorkQueue,注意不要超过整型的最大值。