ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler)
corePoolSize:线池中保留的线程数,核心线程数,可设置 allowCoreThreadTimeOut 超时时间。创建线程池,并没有创建核心线程数,当有任务进来,判断正在运行的线程数少于核心线程数,就尝试 addWorder 添加新线程。
maximumPoolSize:线程池最大线程数(核心线程+非核心线程)
keepAliveTime:线程池中非核心线程空闲时存活时间
unit:线程池中非核心线程空闲时存活时间单位
workQueue:线程池中使用的任务队列1.ArrayBlockingQueue:是有界的任务队列
2.LinkedBlockingQueue:是无界的任务队列
3.SynchronousQueue:无界直接提交队列,当前线程执行后阻塞,不会被复用,所以都会要求线程数无界ThreadFactory:线程工厂,默认使用 Executors.defaultThreadFactory()
handler:拒绝策略1.ThreadPoolExecutor.AbortPolicy(): 默认策略,直接抛出java.util.concurrent.RenjectedExecutionException异常,也不执行这个任务。
2.ThreadPoolExecutor.DiscardPolicy(): 放弃当前任务,并且不会抛出异常。
3.ThreadPoolExecutor.DiscardOldestPolicy(): 会将队列中最早添加的元素移除,再尝试添加,如果失败则按该策略不断重试。
4.ThreadPoolExecutor.CallerRunsPolicy(): 由调用线程处理该任务,如果调用线程是主线程,那么主线程会调用执行器中的execute方法来执行该任务。
CPU密集型公式:CPU核数+1,IO密集型公式:2*CPU核数
四种线程池:
1.Executors.newCachedThreadPool()
// 缓存线程池 public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()); }
2.Executors.newFixedThreadPool()
// 固定线程池 public static ExecutorService newFixedThreadPool(int nThreads) { return new ThreadPoolExecutor(nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()); }
3.Executors.newSingleThreadPool()
// 单线程的线程池 public static ExecutorService newSingleThreadExecutor() { return new FinalizableDelegatedExecutorService (new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>())); }
4.Executors.newScheduledThreadPool(int corePoolSize)
public ScheduledThreadPoolExecutor(int corePoolSize) { super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue()); }
关注可免费获得Java面经一份。