定时线程池执行任务时任务执行时间与定时关系

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Kevin_King1992/article/details/79808426

当执行时间小于定时时间的时候:

System.out.println("执行的时间小于设定的周期");
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);

service.scheduleAtFixedRate(new Runnable() {

    @Override
    public void run() {
        try {
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            Thread.sleep(1000);
            System.out.println("执行业务");
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}, 3000, 2000, TimeUnit.MILLISECONDS);

执行结果:
执行的时间大于设定的周期
2018-04-03 19:58:27
执行业务
2018-04-03 19:58:28
2018-04-03 19:58:29
执行业务
2018-04-03 19:58:30
2018-04-03 19:58:31
执行业务
2018-04-03 19:58:32
2018-04-03 19:58:33
执行业务
2018-04-03 19:58:34
……


当执行任务时间大于定时时间

System.out.println("执行的时间大于设定的周期");
ScheduledExecutorService service = Executors.newScheduledThreadPool(1);

service.scheduleAtFixedRate(new Runnable() {

    @Override
    public void run() {
        try {
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            Thread.sleep(3000);
            System.out.println("执行业务");
            System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}, 300, 1000, TimeUnit.MILLISECONDS);

结果:
执行的时间大于设定的周期
2018-04-03 20:03:43
执行业务
2018-04-03 20:03:46
2018-04-03 20:03:46
执行业务
2018-04-03 20:03:49
2018-04-03 20:03:49
执行业务
2018-04-03 20:03:52
2018-04-03 20:03:52
执行业务
2018-04-03 20:03:55
2018-04-03 20:03:55
执行业务
2018-04-03 20:03:58


结论:每个定时任务在 ScheduledThreadPoolExecutor 中,都是串行运行的,即下一次运行任务一定在上一次任务结束之后。(结论出自https://segmentfault.com/a/1190000008038848

猜你喜欢

转载自blog.csdn.net/Kevin_King1992/article/details/79808426