(二十)java多线程之ScheduledThreadPoolExecutor

本人邮箱: <kco1989@qq.com>
欢迎转载,转载请注明网址 http://blog.csdn.net/tianshi_kco
github: https://github.com/kco1989/kco
代码已经所有托管github有须要的同窗自行下载java

引言

java 提供的线程池还有一个,那就是任务调度线程池ScheduledThreadPoolExecutor,它实际上是ThreadPoolExecutor的一个子类.git

理论

咱们经过查看ScheduledThreadPoolExecutor的源代码,能够发现ScheduledThreadPoolExecutor的构造器都是调用父类的构造器,只是它使用的工做队列是java.util.concurrent.ScheduledThreadPoolExecutor.DelayedWorkQueue经过名字咱们均可以猜到这个是一个延时工做队列.
由于ScheduledThreadPoolExecutor的最大线程是Integer.MAX_VALUE,并且根据源码能够看到executesubmit其实都是调用schedule这个方法,并且延时时间都是指定为0,因此调用executesubmit的任务都直接被执行.github

例子 搞几个延时炸弹

咱们搞几个延时炸弹,让它们每一个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()));
    }
}

运行结果:spa

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.net

ok,这个类相对比较简单,我就很少讲了线程

后记

在正在项目中,通常若是须要使用定时任务,不会直接使用这个类的.有一个quartz已经把定时任务封装的很好了.它是经过cron表示时,能够指定某一个任务天天执行,或者每周三下午5点执行.更多的资料能够去查百度.或者等之后有机会我再整理一写经常使用jar用法系列文章.就这样了.code

打赏

若是以为个人文章写的还过得去的话,有钱就捧个钱场,没钱给我捧我的场(帮我点赞或推荐一下)
微信打赏
支付宝打赏orm

相关文章
相关标签/搜索