Java中Timer和TimerTask使用

Java提供了轻量级的定时任务实现Timer,通过Timer我们可以实现定时执行任务,定时循环执行任务的功能,我们先看JavaDoc中关于Timer的说明

一种工具,线程用其安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。
  与每个 Timer 对象相对应的是单个后台线程,用于顺序地执行所有计时器任务。计时器任务应该迅速完成。如果完成某个计时器任务的时间太长,那么它会“独占”计时器的任务执行线程。因此,这就可能延迟后续任务的执行,而这些任务就可能“堆在一起”,并且在上述不友好的任务最终完成时才能够被快速连续地执行。
  对 Timer 对象最后的引用完成后,并且 所有未处理的任务都已执行完成后,计时器的任务执行线程会正常终止(并且成为垃圾回收的对象)。但是这可能要很长时间后才发生。默认情况下,任务执行线程并不作为守护线程 来运行,所以它能够阻止应用程序终止。如果调用者想要快速终止计时器的任务执行线程,那么调用者应该调用计时器的 cancel 方法。
  如果意外终止了计时器的任务执行线程,例如调用了它的 stop 方法,那么所有以后对该计时器安排任务的尝试都将导致 IllegalStateException,就好像调用了计时器的 cancel 方法一样。
  此类是线程安全的:多个线程可以共享单个 Timer 对象而无需进行外部同步。
  此类不 提供实时保证:它使用 Object.wait(long) 方法来安排任务。
  实现注意事项:此类可扩展到大量同时安排的任务(存在数千个都没有问题)。在内部,它使用二进制堆来表示其任务队列,所以安排任务的开销是 O(log n),其中 n 是同时安排的任务数。
  实现注意事项:所有构造方法都启动计时器线程。

一、一个Timer的简单例子

/**
 * ----------------------------------------
 * 调度线程池
 * ----------------------------------------
 */
private final ThreadPoolExecutor executors = new ThreadPoolExecutor(100, 400, 60L, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>());
/**
 * 线程信息跟踪打印
 */
{
    Timer timer = new Timer(true);
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            LOG.info("==================统计执行线程池信息【开始】==================");
            LOG.info("核心线程数: " + executors.getCorePoolSize());
            LOG.info("最大线程数: " + executors.getMaximumPoolSize());
            LOG.info("活动线程数: " + executors.getPoolSize());
            LOG.info("排队任务数: " + executors.getQueue().size());
            LOG.info("==================统计执行线程池信息【结束】==================");
        }
    }, 1000*60, 1000*60);
}

运行起来后,就会在每60秒跟踪线程池的使用情况,便于在找到最合适的线程池的大小.

二、Timer&TimerTask源码分析
1. Timer部分(此处只截取关键部分代码)

//简单理解:存储需要执行任务的队列
private final TaskQueue queue = new TaskQueue();
//Timer所对应的的线程,所有的任务都是通过它来执行的
private final TimerThread thread = new TimerThread(queue);
public Timer(String name) {
        thread.setName(name);
        thread.start();
}
//只执行一次的任务
public void schedule(TimerTask task, long delay) {
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        sched(task, System.currentTimeMillis()+delay, 0);
}
//循环执行的
public void schedule(TimerTask task, long delay, long period) {
        if (delay < 0)
            throw new IllegalArgumentException("Negative delay.");
        if (period <= 0)
            throw new IllegalArgumentException("Non-positive period.");
        sched(task, System.currentTimeMillis()+delay, -period);
    }
    private void sched(TimerTask task, long time, long period) {
        if (time < 0)
            throw new IllegalArgumentException("Illegal execution time.");

        // Constrain value of period sufficiently to prevent numeric
        // overflow while still being effectively infinitely large.
        if (Math.abs(period) > (Long.MAX_VALUE >> 1))
            period >>= 1;

        //Timer使用的是notify&wait机制进行线程同步
        synchronized(queue) {
            if (!thread.newTasksMayBeScheduled)
                throw new IllegalStateException("Timer already cancelled.");

            synchronized(task.lock) {
                if (task.state != TimerTask.VIRGIN)
                    throw new IllegalStateException(
                        "Task already scheduled or cancelled");
                task.nextExecutionTime = time;
                task.period = period;
                task.state = TimerTask.SCHEDULED;
            }

            queue.add(task);
            if (queue.getMin() == task)
                queue.notify();//唤醒TimerThread开始跑任务
        }
    }

2.TimerThread部分

class TimerThread extends Thread {
    boolean newTasksMayBeScheduled = true;
    private TaskQueue queue;
    TimerThread(TaskQueue queue) {
        this.queue = queue;
    }
    public void run() {
        try {
            mainLoop();
        } finally {
            // Someone killed this Thread, behave as if Timer cancelled
            synchronized(queue) {
                newTasksMayBeScheduled = false;
                queue.clear();  // Eliminate obsolete references
            }
        }
    }

    /**
     * The main timer loop.  (See class comment.)
     */
    private void mainLoop() {
        while (true) {
            try {
                TimerTask task;
                boolean taskFired;
                synchronized(queue) {
                    // Wait for queue to become non-empty
                    while (queue.isEmpty() && newTasksMayBeScheduled)
                        queue.wait();
                    if (queue.isEmpty())
                        break; // Queue is empty and will forever remain; die

                    // Queue nonempty; look at first evt and do the right thing
                    long currentTime, executionTime;
                    task = queue.getMin();
                    synchronized(task.lock) {
                        if (task.state == TimerTask.CANCELLED) {
                            queue.removeMin();
                            continue;  // No action required, poll queue again
                        }
                        currentTime = System.currentTimeMillis();
                        executionTime = task.nextExecutionTime;
                        if (taskFired = (executionTime<=currentTime)) {
                            if (task.period == 0) { // Non-repeating, remove
                                queue.removeMin();
                                task.state = TimerTask.EXECUTED;
                            } else { // Repeating task, reschedule
                                queue.rescheduleMin(
                                  task.period<0 ? currentTime   - task.period
                                                : executionTime + task.period);
                            }
                        }
                    }
                    if (!taskFired) // Task hasn't yet fired; wait
                        queue.wait(executionTime - currentTime);
                }
                if (taskFired)  // Task fired; run it, holding no locks
                    task.run();
            } catch(InterruptedException e) {
            }
        }
    }
}

三、使用Timer的场景与缺陷(个人见解,如有问题还请指出)
适用场景:
1. 任务执行应该比较简单的,耗时的操作建议不要使用。
2. 任务不需要做集群间同步,就如我前面的例子仅仅是跟踪打印信息.
缺陷场景:
1. 由于Timer是单线程执行的,如果其中一个任务抛出了RuntimeException将导致整个Timer退出,如下例:

public static void main(String[] args) throws InterruptedException {
        Timer timer = new Timer();
        final AtomicInteger counter = new AtomicInteger(0);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                int i = counter.incrementAndGet();
                System.out.println("当前线程:" + Thread.currentThread() + ",T1执行中,已将i自增到:" + i);
                if (i == 10) {
                    throw new RuntimeException("我只想抛出个异常玩玩!!");
                }
            }
        }, 1000, 1000);
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                System.out.println("当前线程:" + Thread.currentThread() + "T2已执行执行,当前时间" + this.scheduledExecutionTime());
            }
        }, 1000, 500);

        Thread.sleep(1000 * 20);
    }

执行结果

当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:1
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602890826
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602891326
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602891826
当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:2
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602892326
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602892826
当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:3
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602893326
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602893826
当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:4
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602894326
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602894826
当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:5
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602895326
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602895826
当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:6
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602896326
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602896826
当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:7
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602897326
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602897826
当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:8
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602898326
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602898826
当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:9
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602899326
当前线程:Thread[Timer-0,5,main]T2已执行执行,当前时间1527602899826
Exception in thread “Timer-0” 当前线程:Thread[Timer-0,5,main],T1执行中,已将i自增到:10
java.lang.RuntimeException: 我只想抛出个异常玩玩!!
at TimerTest$1.run(TimerTest.java:20)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)

四、参考链接
1.JDK中的Timer和TimerTask详解
2.java之 Timer 类的使用以及深入理解

猜你喜欢

转载自blog.csdn.net/cockroach02/article/details/80503231
今日推荐