public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
复制代码
特色
核心线程数为0
最大线程数为Integer.MAX_VALUE
阻塞队列是SynchronousQueue
非核心线程空闲存活时间为60秒
工做机制
提交任务
由于没有核心线程,因此任务直接加到SynchronousQueue队列
判断是否有空闲线程,若是有,就去取出任务执行
若是没有空闲线程,就新建一个线程执行
执行完任务的线程,还能够存活60秒,若是在这期间,接到任务,能够继续活下去;不然,被销毁
使用场景
并发执行大量短时间的小任务
newSingleThreadExecutor(单线程的线程池)
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
复制代码
特色
核心线程数为1
最大线程数也为1
keepAliveTime为0
阻塞队列是LinkedBlockingQueue
工做机制
提交任务
线程池是否有一条线程在,若是没有,新建线程执行任务
若是有,任务加到阻塞队列
当前的惟一线程,从队列取任务,执行完一个,再继续取,一我的(一条线程)夜以继日地干活
使用场景
newScheduledThreadPool(定时及周期执行的线程池)
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
public ScheduledThreadPoolExecutor(int corePoolSize,
ThreadFactory threadFactory) {
super(corePoolSize, Integer.MAX_VALUE, 0, NANOSECONDS,
new DelayedWorkQueue(), threadFactory);
}
复制代码
特色
最大线程数为Integer.MAX_VALUE
阻塞队列是DelayedWorkQueue
keepAliveTime为0
scheduleAtFixedRate() :按某种速率周期执行
scheduleWithFixedDelay():在某个延迟后执行
工做机制
添加一个任务
线程池中的线程从 DelayQueue 中取任务
线程从 DelayQueue 中获取 time 大于等于当前时间的task
执行完后修改这个 task 的 time 为下次被执行的时间
这个 task 放回DelayQueue队列中
使用场景
周期性执行任务的场景,须要限制线程数量的场景
自定义ThreadPool
copy一份AbortPolicy改个名字,加些本身想加的内容(例如加个输出)。
public static class MyPolicy implements RejectedExecutionHandler {
public MyPolicy() { }
public void rejectedExecution(Runnable r, java.util.concurrent.ThreadPoolExecutor e) {
// 新增
System.out.println("拒绝");
throw new RejectedExecutionException("Task " + r.toString() +
" rejected from " +
e.toString());
}
}
复制代码
copy一份DefaultThreadFactory改个名字,加些本身想加的内容(例如加个输出)。
static class MyThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
MyThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
// 新增
System.out.println(t.getName() + " has been created");
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
复制代码
测试
public static void main(String agrs[]) throws Exception{
int corePoolSize = 2;
int maximumPoolSize = 4;
long keepAliveTime = 10;
TimeUnit unit = TimeUnit.SECONDS;
BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
ThreadFactory threadFactory = new MyThreadFactory();
ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit,
workQueue, threadFactory,new MyPolicy());
executor.prestartAllCoreThreads(); // 预启动全部核心线程
for (int i = 1; i <= 10; i++) {
executor.execute(()-> System.out.println(Thread.currentThread().getId()));
}
System.in.read(); //阻塞主线程
}
复制代码