处理内容:线程池工厂类。
备注:
也可以用工具类创建线程池,Excutors来创建,因为Excutors创建线程池也是底层用的也是
ThreadPoolExecutor,所有就干脆用这个了,顺便了解一下。
newCachedThreadPool创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。
newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
注意,本工具类使用的队列是LinkedBlockingQueue,这个队列是×××队列,就是没有指定容量,可以无限大。因此这个参数就是无效的maximumPoolSize。为什么会采用这种,因为我现在工作线程的处理速度比放入工作线程的任务快。
(corePoolSize, maximumPoolSize, keepAliveTime)参数意义,可以自己去找,网上一大堆,不再陈述。
开发过程中,用线程池可以减少创建和销毁线程的开销。直接上代码把。
/**
* 处理内容:线程池工厂类
*
* @author shangdc
*
*/
@Component("multiThreadPoolExecutorFactory")
public class MultiThreadPoolExecutorFactory {
/**
private static final int corePoolSize = 50;
/**
private static final int maximumPoolSize = 100;
/**
private static final int keepAliveTime = 60;
/**
private static final int capacity = 300;
/**
private static ThreadPoolExecutor threadPoolExecutor = null;
// 构造方法私有化
private MultiThreadPoolExecutorFactory() {
}
public static ThreadPoolExecutor getThreadPoolExecutor() {
if (null == threadPoolExecutor) {
ThreadPoolExecutor t;
synchronized (ThreadPoolExecutor.class) {
t = threadPoolExecutor;
if (null == t) {
synchronized (ThreadPoolExecutor.class) {
t = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
}
threadPoolExecutor = t;
}
}
}
return threadPoolExecutor;
}
}
转载于:https://blog.51cto.com/shangdc/1911433