核心参数说明
参数名 | 原注释 | 翻译 |
---|
corePoolSize | the number of threads to keep in the pool, even if they are idle, unless allowCoreThreadTimeOut is set | 线程中线程的数量,即使他们是空闲的,除非设置了核心线程存活时间 |
maximumPoolSize | the maximum number of threads to allow in the pool | 线程池中最大的线程数量,当核心线程不够时,会创建临时线程 |
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. | 当存在临时线程时,临时线程在没有接受到任务时,存活的最大时间 |
unit | the time unit for the keepAliveTime argument | 时间单位 |
workQueue – | the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method. | 用来存放任务的队列 |
threadFactory | the factory to use when the executor creates a new thread | 创建线程的工厂 |
handler | the handler to use when execution is blocked because the thread bounds and queue capacities are reached | 当核心线程在忙,等待队列也满了之后,如果还有任务进来的处理策略,此处为默认的策略 |
演示代码
package thread;
import java.util.concurrent.*;
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService pool=new ThreadPoolExecutor(
3,
5,
6,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(5),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
Runnable target=new MuRunnable();
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target) ;
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
pool.execute(target);
}
}
创建线程池的其他方法
方法名称 | 说明 |
---|
public static ExecutorService newCachedThreadPool() | 线程数量随着任务的增加而增加,如果线程任务执行完毕切空闲了一段时间则会被回收掉 |
public static ExecutorService newFixedThreadPool(int nThreads) | 创建固定线程数量的线程池,如果某个线程因为执行异常而结束,那么线程池会补充一个 新的线程来替代它 |
public static ExecutorService newSingleThreadExecutor() | 创建之有一个线程的线程池对象,如果该线程出现异常而终结,那么线程池会补充一个新的线程 |
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) | 创建一个线程池,可以实现在给定的延迟时间后运行任务,或者定期执行任务 |
Executors使用可能存在的陷阱
大型并发系统环境中使用Executors如果不注意可能会出现系统风险。
方法名称 | 存在问题 |
---|
public static ExecutorService newFixedThreadPool(int nThreads) | 允许请求的任务队列长度是IntegerMAXVALUE,可能出现OOM 错误(java.lang.OutOfMemoryError) |
public static ExecutorService newSingleThreadExecutor() | 允许请求的任务队列长度是IntegerMAXVALUE,可能出现OOM 错误(java.lang.OutOfMemoryError) |
public static ExecutorService newCachedThreadPool() | 创建的线程数量最大上限是Integer.MAXVALUE,线程数可能会随着任务1:1增长,也可能出现OOM错误 |
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) | (iava.lang.OutOfMemoryError) |
阿里巴巴Java开发手册
【强制】 线程池不允许使用 Executors去创建,而是通过ThreadPoolExecutor的方式,这样
的处理方式让写的同学更加明确线程池的运行规则,规避资源耗尽的风险。
说明:Executors返回的线程池对象的弊端如下:
- FixedThreadPool和SingleThreadPool:
允许的请求队列长度为Integer.MAX_VALUE,可能会堆积大量的请求,从而导致00M。
2.CachedThreadPool和ScheduledThreadPool:
允许的创建线程数量为Integer.MAX_VALUE,可能会创建大量的线程,从而导致00M。
线程的状态以及切换
