Executors
Executors
newCachedThreadPool 创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。newFixedThreadPool 创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。newScheduledThreadPool 创建一个定长线程池,支持定时及周期性任务执行。newSingleThreadExecutor 创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级) 执行。
public static void main(String[] args) {
// 创建可以容纳3个线程的线程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
// 线程池的大小会根据执行的任务数动态分配
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
// 创建单个线程的线程池,如果当前线程在执行任务时突然中断,则会创建一个新的线程替代它继续执行任务
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
// 效果类似于Timer定时器
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(
3
);
run(fixedThreadPool);
// run(cachedThreadPool); // 执行结果,可以看出 4 个任务交替执行
// run(singleThreadPool);
// run(scheduledThreadPool);
}
CachedThreadPool
- 重用:缓存型池子,先查看池中有没有以前建立的线程,如果有,就
reuse ;如果没有,就建一个新的线程加入池中 - 使用场景:缓存型池子通常用于执行一些生存期很短的异步型任务,因此在一些面向连接的
daemon 型SERVER 中用得不多。 - 超时:能
reuse 的线程,必须是timeout IDLE 内的池中线程,缺省timeout 是60s ,超过这个IDLE 时长,线程实例将被终止及移出池。 - 结束:注意,放入
CachedThreadPool 的线程不必担心其结束,超过TIMEOUT 不活动,其会自动被终止。
// 线程池的大小会根据执行的任务数动态分配
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, //core pool size
Integer.MAX_VALUE, //maximum pool size
60L, //keep alive time
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}
FixedThreadPool
在
- 重用:
fixedThreadPool 与cacheThreadPool 差不多,也是能reuse 就用,但不能随时建新的线程 - 固定数目:其独特之处在于,任意时间点,最多只能有固定数目的活动线程存在,此时如果有新的线程要建立,只能放在另外的队列中等待,直到当前的线程中某个线程终止直接被移出池子
- 超时:和
cacheThreadPool 不同,FixedThreadPool 没有IDLE 机制( 可能也有,但既然文档没提,肯定非常长,类似依赖上层的TCP 或UDP IDLE 机制之类的) ,
所以
fixed 池线程数固定,并且是0 秒IDLE( 无IDLE) cache 池线程数支持0-Integer.MAX_VALUE( 显然完全没考虑主机的资源承受能力) ,60 秒IDLE
// 创建可以容纳3个线程的线程池
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, //core pool size
nThreads, //maximum pool size
0L, //keep alive time
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
执行结果:创建了一个固定大小的线程池,容量为
SingleThreadExecutor
// 创建单个线程的线程池,如果当前线程在执行任务时突然中断,则会创建一个新的线程替代它继续执行任务
ExecutorService singleThreadPool = Executors.newSingleThreadExecutor();
// 内部实现
public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, //core pool size
1, //maximum pool size
0L, //keep alive time
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}
ScheduledThreadPool
// 效果类似于Timer定时器
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(3);
public ScheduledThreadPoolExecutor(int corePoolSize) {
super(corePoolSize, //core pool size
Integer.MAX_VALUE, //maximum pool size
0, //keep alive time
TimeUnit.NANOSECONDS,
new DelayedWorkQueue());
}
为了持续的多次执行常见的任务,我们可以利用调度线程池
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime());
// 设置延迟 3 秒执行
ScheduledFuture<?> future = executor.schedule(task, 3, TimeUnit.SECONDS);
TimeUnit.MILLISECONDS.sleep(1337);
long remainingDelay = future.getDelay(TimeUnit.MILLISECONDS);
System.out.printf("Remaining Delay: %sms", remainingDelay);
调度一个任务将会产生一个专门的cheduleAtFixedRate()
scheduleWithFixedDelay()
;第一个方法用来以固定频率来执行一个任务,比如,下面这个示例中,每分钟一次:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
Runnable task = () -> System.out.println("Scheduling: " + System.nanoTime());
int initialDelay = 0;
int period = 1;
executor.scheduleAtFixedRate(task, initialDelay, period, TimeUnit.SECONDS);
另外,这个方法还接收一个初始化延迟,用来指定这个任务首次被执行等待的时长。需要注意的是,scheduleAtFixedRate()
并不考虑任务的实际用时。所以,如果你指定了一个