java中的定时器

2019-09-30  本文已影响0人  缘木与鱼

1、java中普通定时任务

Timer定时器

// Timer 和 TimerTask是java.util两个类
Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
        System.out.println("aaa");
    }
}, 2000, 40);

// schedule(TimerTask task, long delay, long period)
// 第一个参数:要执行的任务
// 第二个参数:任务执行前的延迟 (单位:ms)
// 第三个参数:连续任务执行之间的时间间隔 (单位:ms)

ScheduledThreadPoolExecutor 定时器

// ScheduledThreadPoolExecutor定时器可以设置线程池的大小,该类extends ThreadPoolExecutor implements ScheduledExecutorService
ScheduledThreadPoolExecutor scheduled = new ScheduledThreadPoolExecutor(2);
scheduled.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}, 1000, 1000, TimeUnit.MILLISECONDS);

// scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)
// 参数1: 执行的任务
// 参数2: 任务执行前的延迟
// 参数3: 连续任务执行之间的时间间隔
// 参数4: 前面两个时间的单位

Timer定时器与ScheduledThreadPoolExecutor 定时器比较

1、Timer只创建一个线程,当任务的执行时间超出设置间隔的时间可能会有问题
2、Timer创建的线程没有处理异常,因此一旦抛出非受检异常,该线程会立即终止
3、在频繁处理时间间隔的时候ScheduledThreadPoolExecutor的误差更小

上一篇 下一篇

猜你喜欢

热点阅读