1 Executors的几种常见线程池分类以及创建方式
/**
* 单线程线程池,可以用来处理日志文件。 保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行, 所以这个比较适合那些需要按序执行任务的场景
*
* @return
*/
public static ExecutorService singleThreadPool() {
return Executors.newSingleThreadExecutor();
}
/**
* 固定线程数线程池
*
* @param n cpu倍数
* @return
*/
public static ExecutorService fixedThreadPool(int n) {
int process = Runtime.getRuntime().availableProcessors();
return Executors.newFixedThreadPool(process * n);
}
/**
* 缓存的线程池 适合处理执行时间比较小的任务 如果主线提交任务,大于缓存线程池处理的速度,CPU和内存将会耗尽
*
* @return
*/
public static ExecutorService cachedThreadPool() {
return Executors.newCachedThreadPool();
}
/**
* 固定个数的线程池 相比cpu倍数的,好处 1:可以执行延迟任务。 2:执行带返回值的任务
*
* @return
*/
public static ScheduledExecutorService scheduledThreadPool() {
return Executors.newScheduledThreadPool(5);
}
2 Executors创建线程池,实际都是对new ThreadPoolExecutor的实现
/**
* Creates a new {@code ThreadPoolExecutor} with the given initial
* parameters.
*
* @param corePoolSize the number of threads to keep in the pool, even
* if they are idle, unless {@code allowCoreThreadTimeOut} is set
* @param maximumPoolSize the maximum number of threads to allow in the
* pool
* @param keepAliveTime when the number of threads is greater than
* the core, this is the maximum time that excess idle threads
* will wait for new tasks before terminating.
* @param unit the time unit for the {@code keepAliveTime} argument
* @param workQueue the queue to use for holding tasks before they are
* executed. This queue will hold only the {@code Runnable}
* tasks submitted by the {@code execute} method.
* @param threadFactory the factory to use when the executor
* creates a new thread
* @param handler the handler to use when execution is blocked
* because the thread bounds and queue capacities are reached
* @throws IllegalArgumentException if one of the following holds:<br>
* {@code corePoolSize < 0}<br>
* {@code keepAliveTime < 0}<br>
* {@code maximumPoolSize <= 0}<br>
* {@code maximumPoolSize < corePoolSize}
* @throws NullPointerException if {@code workQueue}
* or {@code threadFactory} or {@code handler} is null
*/
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
方法中参数的含义:
int corePoolSize:线程中要保留的线程数 int maximumPoolSize:线程池允许的最大线程数 long keepAliveTime:线程超过最大线程数后,线程等待的事件。 TimeUnit unit:对keepAliveTime的定义,比如时分秒 BlockingQueue<Runnable> workQueue:保存线程的队列,只保存通过execute执行的runnable任务 ThreadFactory threadFactory:创建线程池时,使用的线程工厂 RejectedExecutionHandler handler:当出现异常时执行的方法
3 线程池的使用
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = fixedThreadPool(2);
for (int i = 1; i < 1000; i++) {
int finalI = i;
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(finalI);
}
});
}
for (int i = 1; i < 1000; i++) {
int finalI = i;
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println();
}
};
executorService.submit(runnable);
}
// 第四种线程池:固定个数的线程池,相比于第一个固定个数的线程池 强大在 ①可以执行延时任务,②也可以执行
// 有返回值的任务。
// scheduledThreadPool.submit(); 执行带有返回值的任务
// scheduledThreadPool.schedule() 用来执行延时任务.
// 固定个数的线程池,可以执行延时任务,也可以执行带有返回值的任务。
// ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
// FutureTask<String> ft = new FutureTask<>(new Callable<String>() {
// @Override
// public String call() throws Exception {
// System.out.println("hello");
// return Thread.currentThread().getName();
// }
// });
// scheduledThreadPool.submit(ft);
//
// // 通过FutureTask对象获得返回值.
// String result = ft.get();
// System.out.println("result : " + result);
//
// // 执行延时任务
// scheduledThreadPool.schedule(new Runnable() {
// @Override
// public void run() {
// System.out.println(Thread.currentThread().getName() + " : bobm!");
// }
// }, 3L, TimeUnit.SECONDS);
}
execute和submit都是对任务的提交。区别有三点
1 execute只能提交Runnable类型的任务,submit既能提交Runnable又能提交Callable类型的任务
2 异常的捕捉:execute会直接抛出异常,submit会吃掉异常,通过Future的get方法将异常抛出
3 返回值:execute没有返回值,submit有返回值(用法在注释中)
结语:有不足之处,望补充。