延迟任务与周期任务-Timer&ScheduledThread定时器使用

背景:

Timer类负责延迟任务和周期任务,但是Timer存在一些缺陷,因此应该考虑使用ScheduledThreadPoolExecutor来代替它。

 

Timer缺陷:

1、Timer在执行所有定时任务时只会创建一个线程。如果某个任务的执行时间过长,那么将破坏其他TimerTask的定时精确性。

2、如果TimerTask抛出了一个未检查异常,那么Timer将表现出糟糕行为。Timer线程并不捕获异常,因此TimerTask抛出未检查异常时将终止定时线程。

 

时钟调度区别:

Timer支持基于绝对时间而不是相对时间的调度机制,因此任务的执行对系统时钟变化很敏感,而ScheduledThreadPoolExecutor 只支持基于相对时间的调度。

 

代码示例:

package com.csdn.test.timer;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;


public class TestScheTask
{
    private static final int TRY_SEND_DATA_PERIOD = 2000;

    // 重试间隔时间(毫秒)
    private static final int TIMEOUT = 300000;

    // 单位统一为毫秒
    private static final TimeUnit UNIT = TimeUnit.MILLISECONDS;
    
    private static final int MAX_TIME = 5;

    private volatile AtomicBoolean isFinish = new AtomicBoolean(false);

    private volatile CountDownLatch done = new CountDownLatch(1);
    
    private int scheduledES_count1 = 0;
    
    private int scheduledES_count2 = 0;
    
    private int timer_count1 = 0;
    
    private int timer_count2 = 0;

    public void scheduleTaskByScheduledES()
    {
        // 单线程线程池
        ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
        exec.scheduleAtFixedRate(new Runnable()
        {

            @Override
            public void run()
            {
                boolean isOk = isFinish.get();
                if (!isOk)
                {
                    
                    System.out.println("ScheduleTaskByScheduledES: try start ... count1 is: " + scheduledES_count1);
                    scheduledES_count1 ++;
                    if (scheduledES_count1 > 1)
                    {
                        throw new RuntimeException("current count1 is: " + scheduledES_count1);
                    }
                    if (scheduledES_count1 > MAX_TIME)
                    {
                        isFinish.getAndSet(true);
                        done.countDown();
                        System.out.println("Scheduled thread: end success");
                    }
                    
                }
            }

        }, 0, TRY_SEND_DATA_PERIOD, UNIT);

        exec.scheduleAtFixedRate(new Runnable()
        {

            @Override
            public void run()
            {
                boolean isOk = isFinish.get();
                if (!isOk)
                {
                    
                    System.out.println("ScheduleTaskByScheduledES: try start ... count2 is: " + scheduledES_count2);
                    scheduledES_count2 ++;
                    if (scheduledES_count2 > MAX_TIME)
                    {
                        isFinish.getAndSet(true);
                        done.countDown();
                        System.out.println("Scheduled thread: end success");
                    }
                    
                }
            }

        }, 0, TRY_SEND_DATA_PERIOD, UNIT);
        
        System.out.println("Watch countDownLatch thread start");
        new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                try
                {
                    // 等待上报数据成功
                    done.await();
                    System.out.println("Watch countDownLatch thread: try shutdown scheduled executor");
                    // 安全关闭线程池
                    exec.shutdown();
                    // 超时退出
                    exec.awaitTermination(TIMEOUT, UNIT);
                    System.out.println("Watch countDownLatch thread: end shutdown scheduled executor");
                }
                catch (InterruptedException e)
                {
                    System.out.println("Watch countDownLatch thread is interrupted, exception is: "
                            + e);
                }

            }

        }).start();
        System.out.println("Scheduled thread and watch countDownLatch thread both start");
    }
    
    public void scheduleTaskByTimer()
    {
        Timer timer = new Timer();
        timer.schedule(new TimerTask(){

            @Override
            public void run()
            {
                System.out.println("ScheduleTaskByTimer1: try start ... count1 is: " + timer_count1);
                timer_count1++;
                if (timer_count1 > 1)
                {
                    throw new RuntimeException("current count is: " + timer_count1);
                }
            }
            
        }, 0, TRY_SEND_DATA_PERIOD);
        timer.schedule(new TimerTask(){

            @Override
            public void run()
            {
                System.out.println("ScheduleTaskByTimer2: try start ... count2 is: " + timer_count2);
                timer_count2++;
            }
            
        }, 0, TRY_SEND_DATA_PERIOD);
    }
    
    public static void main(String args[])
    {
        TestScheTask test1 = new TestScheTask();
        new Thread(new Runnable(){

            @Override
            public void run()
            {
                test1.scheduleTaskByScheduledES();
            }
            
        }).start();
        TestScheTask test2 = new TestScheTask();
        new Thread(new Runnable(){

            @Override
            public void run()
            {
                test2.scheduleTaskByTimer();
            }
            
        }).start();
    }
}

输出:

ScheduleTaskByTimer1: try start ... count1 is: 0
ScheduleTaskByTimer2: try start ... count2 is: 0
ScheduleTaskByScheduledES: try start ... count1 is: 0
Watch countDownLatch thread start
ScheduleTaskByScheduledES: try start ... count2 is: 0
Scheduled thread and watch countDownLatch thread both start
ScheduleTaskByTimer2: try start ... count2 is: 1
ScheduleTaskByTimer1: try start ... count1 is: 1
Exception in thread "Timer-0" ScheduleTaskByScheduledES: try start ... count1 is: 1   ------异常捕获
ScheduleTaskByScheduledES: try start ... count2 is: 1
java.lang.RuntimeException: current count is: 2                                                          -------异常抛出 线程终止 导致Timer cannel
    at com.csdn.test.timer.TestScheTask$4.run(TestScheTask.java:138)
    at java.util.TimerThread.mainLoop(Unknown Source)
    at java.util.TimerThread.run(Unknown Source)
ScheduleTaskByScheduledES: try start ... count2 is: 2                                                ------另一线程继续执行 
ScheduleTaskByScheduledES: try start ... count2 is: 3
ScheduleTaskByScheduledES: try start ... count2 is: 4
ScheduleTaskByScheduledES: try start ... count2 is: 5
Scheduled thread: end success
Watch countDownLatch thread: try shutdown scheduled executor                    
Watch countDownLatch thread: end shutdown scheduled executor

                                                                                                                                   ---------- Timer的另一TimerTask不再执行

 

结果分析:

1、同一Timer对象不适合启动多个TimerTask任务,一是因为单线程执行这些任务,二是因为任何一个TimerTask抛出未受检异常,Timer不会进行捕获,会导致Timer cannel,后续任务无法继续进行

2、延迟或定时任务推荐使用 ScheduledExecutorService 对象的 scheduleAtFixedRate 方法,安全高效。

 

 

参考书籍:

《Java并发编程实战》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值