Java--Timer与ScheduledExecutorService定时任务

本文探讨了Timer和ScheduledExecutorService两种定时任务处理方式的差异。指出Timer在多任务执行时存在的缺陷,如任务阻塞和异常导致后续任务无法执行的问题,并通过示例代码展示这些现象。同时介绍了ScheduledExecutorService如何解决这些问题,确保即使发生异常也能继续执行后续任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Timer的缺陷

    a)Timer在多任务情况下,如果任务(TimerTask)的执行时间超过任务间隔时间时,则需要等待前任务执行完成才会执行后任务

    b)Timer在多任务情况下,若有任务出现异常的时候,则不会执行以下任务

    以下为事例代码:

    a <Demo>

public class Main3Activity extends AppCompatActivity {
    private Timer timer;

    private static final String TAG = "Main3Activity";
    private static long startTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        timer = new Timer();
        TimerTask timerTask1 = new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "run: " + (System.currentTimeMillis() - startTime));
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        };

        TimerTask timerTask2 = new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "run: " + (System.currentTimeMillis() - startTime));
            }
        };
        startTime = System.currentTimeMillis();
        timer.schedule(timerTask1, 1000);
        timer.schedule(timerTask2, 3000);
    }
}

    打印的log信息如下:

06-08 14:03:06.480 14116-14184/com.tago.lable.testfirst E/Main3Activity: run: 1000
06-08 14:03:10.482 14116-14184/com.tago.lable.testfirst E/Main3Activity: run: 5002

    <Demo>

public class Main3Activity extends AppCompatActivity {
    private Timer timer;

    private static final String TAG = "Main3Activity";
    private static long startTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        timer = new Timer();
        TimerTask timerTask1 = new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "run: " + (System.currentTimeMillis() - startTime));
                throw new RuntimeException();
            }
        };

        TimerTask timerTask2 = new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "run: " + (System.currentTimeMillis() - startTime));
            }
        };
        startTime = System.currentTimeMillis();
        timer.schedule(timerTask1, 1000);
        timer.schedule(timerTask2, 3000);
    }
}

程序在打印出第一个TimerTask输出语句之后,直接崩溃。

2.ScheduledExecutorService用法

    a <Demo> 多任务执行顺序

public class Main3Activity extends AppCompatActivity {

    private static final String TAG = "Main3Activity";
    private static long startTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        TimerTask timerTask1 = new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "run: " + (System.currentTimeMillis() - startTime));
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };

        TimerTask timerTask2 = new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "run: " + (System.currentTimeMillis() - startTime));
            }
        };
        startTime = System.currentTimeMillis();
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(2);
        scheduledExecutorService.schedule(timerTask1, 1000, TimeUnit.MILLISECONDS);
        scheduledExecutorService.schedule(timerTask2, 3000, TimeUnit.MILLISECONDS);
    }
}

    log

06-08 14:12:09.115 16092-16145/com.tago.lable.testfirst E/Main3Activity: run: 1002
06-08 14:12:11.116 16092-16146/com.tago.lable.testfirst E/Main3Activity: run: 3003

    b <Demo> 多任务下前任务出现异常

public class Main3Activity extends AppCompatActivity {

    private static final String TAG = "Main3Activity";
    private static long startTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        TimerTask timerTask1 = new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "run: " + (System.currentTimeMillis() - startTime));
                throw new RuntimeException();
            }
        };

        TimerTask timerTask2 = new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "run: " + (System.currentTimeMillis() - startTime));
            }
        };
        startTime = System.currentTimeMillis();
        ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(2);
        scheduledExecutorService.schedule(timerTask1, 1000, TimeUnit.MILLISECONDS);
        scheduledExecutorService.schedule(timerTask2, 3000, TimeUnit.MILLISECONDS);
    }
}

    不影响程序运行

    log

06-08 14:14:11.745 16563-16590/com.tago.lable.testfirst E/Main3Activity: run: 1001
06-08 14:14:13.745 16563-16591/com.tago.lable.testfirst E/Main3Activity: run: 3001 

    构造参数说明:

 ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(2);

    官方说明:    

/**
     * Creates a new {@code ScheduledThreadPoolExecutor} with the
     * given core pool size.
     *
     * @param corePoolSize the number of threads to keep in the pool, even
     *        if they are idle, unless {@code allowCoreThreadTimeOut} is set
     * @throws IllegalArgumentException if {@code corePoolSize < 0}
     */

ScheduledExecutorService本事一个接口,我们在使用需要创建一个他的实现类。这个构造要求我们传入一个int值,这个值为  ScheduledThreadPoolExecutor创建的线程池的大小。

使用方法说明:

scheduledExecutorService.schedule(timerTask1, 1000, TimeUnit.MILLISECONDS);
第一个参数为执行的操作,第二参数为执行时间,第三个参数为执行时间的单位

    /**
     * Time unit representing one thousandth of a microsecond.
     *  微秒
     */
    NANOSECONDS

    /**
     * Time unit representing one thousandth of a millisecond.
     *  毫秒
     */
    MICROSECONDS 

    /**
     * Time unit representing one thousandth of a second.
     *  秒	
     */
    MILLISECONDS 

    /**
     * Time unit representing one second.
     */
    SECONDS 

    /**
     * Time unit representing sixty seconds.
     * 60 秒(分)
     * @since 1.6
     */
    MINUTES 

    /**
     * Time unit representing sixty minutes.
     * 60 分 (小時)
     * @since 1.6
     */
    HOURS 

    /**
     * Time unit representing twenty four hours.
     * 24 小时(天)
     * @since 1.6
     */
    DAYS 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值