java 提供的线程池还有一个,那就是任务调度线程池ScheduledThreadPoolExecutor,它其实是ThreadPoolExecutor的一个子类.
我们通过查看ScheduledThreadPoolExecutor的源代码,可以发现ScheduledThreadPoolExecutor的构造器都是调用父类的构造器,只是它使用的工作队列是java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue通过名字我们都可以猜到这个是一个延时工作队列.
因为ScheduledThreadPoolExecutor的最大线程是Integer.MAX_VALUE,而且根据源码可以看到execute和submit其实都是调用schedule这个方法,而且延时时间都是指定为0,所以调用execute和submit的任务都直接被执行.
我们搞几个延时炸弹,让它们每个5s炸一次
public class TestMain { public static void main(String[] args) throws InterruptedException { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); ScheduledThreadPoolExecutor pool = new ScheduledThreadPoolExecutor(5); for (int i = 0; i < 5; i ++){ final int temp = i + 1; pool.schedule(() -> { System.out.println("第"+temp+"个炸弹爆炸时间:" + simpleDateFormat.format(new Date())); }, temp * 5, TimeUnit.SECONDS); } pool.shutdown(); System.out.println("end main时间:" + simpleDateFormat.format(new Date())); } }
运行结果:
end main时间:2016-11-03 19:58:31
第1个炸弹爆炸时间:2016-11-03 19:58:36
第2个炸弹爆炸时间:2016-11-03 19:58:41
第3个炸弹爆炸时间:2016-11-03 19:58:46
第4个炸弹爆炸时间:2016-11-03 19:58:51
第5个炸弹爆炸时间:2016-11-03 19:58:56
ok,这个类相对比较简单,我就不多讲了
在正在项目中,一般如果需要使用定时任务,不会直接使用这个类的.有一个quartz已经把定时任务封装的很好了.它是通过cron表示时,可以指定某一个任务每天执行,或者每周三下午5点执行.更多的资料可以去查百度.或者等以后有机会我再整理一写常用jar用法系列文章.就这样了.