zoukankan      html  css  js  c++  java
  • 利用 java.util.Timer来写一个定时器

    @大神爱吃茶

      java.util.Timer中的TimerTask类

      这个包java.util.Timer是Java中的一个实用工具类,用来调度将来某个时间执行的线程。

      TimerTask类的源码:

    public abstract class TimerTask implements Runnable {
        final Object lock = new Object();
    
        int state = VIRGIN;   
    
        static final int VIRGIN = 0;
    
        static final int SCHEDULED   = 1;
    
        static final int EXECUTED    = 2;
    
        static final int CANCELLED   = 3;    
    
        long nextExecutionTime;
    
        long period = 0;
    
        protected TimerTask() {
        }
    
        public abstract void run();
        public boolean cancel() {
            synchronized(lock) {
                boolean result = (state == SCHEDULED);
                state = CANCELLED;
                return result;
            }
        }
    
        public long scheduledExecutionTime() {
            synchronized(lock) {
                return (period < 0 ? nextExecutionTime + period
                                   : nextExecutionTime - period);
            }
        }
    
    }
    

      TimerTask是实现了Runnable接口的,使用时是使用的Timer类,Java Timer类是线程安全的,多个线程可以共享一个Timer对象,而无需外部同步。使用时需要创建一个Timer对象。

    使用实例:

    import java.util.Timer;
    import java.util.TimerTask;
    
    public class Test extends TimerTask {
        private String name = "";
    
        public Test(String name) {
            this.name = name;
        }
    
        @Override
        public void run() {
            System.out.println("execute:" + name);
        }
    
        public static void main(String[] args) {
            Timer timer = new Timer();
            long delay1 = 1 * 1000;
            long period1 = 1000;
            // 从现在开始 1 秒钟之后,每隔 1 秒钟执行一次 job1
            timer.schedule(new Test("test.."), delay1, period1);
            long delay2 = 2 * 1000;
            long period2 = 2000;
            // 从现在开始 2 秒钟之后,每隔 2 秒钟执行一次 job2
            timer.schedule(new Test("testResult.."), delay2, period2);
        }
    }

    输出结果:

       Timer类包含几个schedule()方法,用于安排任务在给定时间或延迟一段时间后运行一次:

    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);
    }
    

      

  • 相关阅读:
    mono for android学习过程系列教程(6)
    mono for android学习过程系列教程(5)
    mono for android学习过程系列教程(4)
    mono for android学习过程系列教程(3)
    mono for android学习过程系列教程(2)
    mono for android学习过程系列教程(1)
    随笔索引
    中国大学MOOC中的后台文件传输
    知乎控件分享(一)
    知乎UWP 预览
  • 原文地址:https://www.cnblogs.com/dashenaichicha/p/11975791.html
Copyright © 2011-2022 走看看