一、几种常用线程池
- Executors.newSingleThreadExecutor() 单个的线程池 使用的LinkedBlockingQueue
- Executors.newFixedThreadPool(10) 固定数量线程池 使用的LinkedBlockingQueue
- Executors.newCachedThreadPool() 可缓存的线程池 使用的SynchronousQueue。如果线程池长度超过处理需要,可灵活回收空闲线程(构造器中默认是60S的参数),若无可回收,则新建线程
- 通过ThreadPoolExecutor构造器,前面三个也是通过构造方法创建
// ThreadPoolExecutor内部使用AQS public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize,long keepAliveTime,TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
二、线程池流程
三、拒绝策略
- AbortPolicy(抛出一个异常,默认的)
- DiscardPolicy(直接丢弃任务)
- DiscardOldestPolicy(丢弃队列里最老的任务,将当前这个任务继续提交给线程池)
- CallerRunsPolicy(交给线程池调用所在的线程进行处理)
四、newFixedThreadPool导致的OOM(Out Of Memory)
- newFixedThreadPool使用了无界的阻塞队列LinkedBlockingQueue,大小为Integer.MAX_VALUE,如果任务很多会导致队列的任务越积越多,导致机器内存使用不停飙升。
- 可使用ThreadPoolExecutor构造器自己创建,使用有界队列ArrayBlockingQueue
参考内容
- https://www.cnblogs.com/jay-huaxiao/p/11454416.html