最近在做一个小功能,是关于定时调度任务的。主要逻辑:
- 用定时线程池的定时功能,每30s 检查一次有没有任务需要调度(根据上次调度时间计算下次执行时间)
- 将符合条件的任务添加到FixedThreadPool线程池中进行调度
由于任务是由leader 负责检查和调度的,leader 切换时会关闭线程池。因此我们领导觉得这么做不合理,应该有个队列,将符合条件的任务加入队列,然后后台慢慢处理。
我们来看看FixedThreadPool 是如何初始化的
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}
。。。。。
关于shutdown 测试
@Test
public void testPool() throws InterruptedException {
ExecutorService DEFAULT = Executors.newFixedThreadPool(1);
for (int i = 0; i < 10; i++) {
Runnable task = () -> {
System.out.println(k);
k++;
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
System.out.println("...");
}
};
DEFAULT.submit(task);
}
System.out.println("start shutdown");
DEFAULT.shutdown();
System.out.println("shutdown");
TimeUnit.SECONDS.sleep(5000);
输出
0
start shutdown
shutdown
1
2
3
4
5
6
7
8
9