• java定时器schedule和scheduleAtFixedRate区别


    package cn.lonecloud.test;
    
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    /**
     * 
     * @Title: Test02.java
     * @Package cn.lonecloud.test
     * @Description: 
     * @author lonecloud
     * @date 2016年8月5日 下午4:43:29
     */
    public class Test02 {
    	public static void main(String[] args) throws Exception{
    		timer3();
    	}
    	/**
    	 * scheduleAtFixedRate
    	 * 对于这个来说这里的时间是根据你的传入的时间来算
    	 * 不管你是否线程休眠与否都要一开始执行
    	 * @Description: 
    	 * @throws Exception
    	 */
        public static void timer3() throws Exception{
        	Date date = new Date();
            Timer timer = new Timer();
            Thread.sleep(9000);
            timer.scheduleAtFixedRate(new TimerTask() {
                public void run() {
                	
    	                System.out.println(new Date());
                }
            }, date, 1000);
        }
        /**
         * 运行9秒后运行结果
         *  Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:41 CST 2016
    		Fri Aug 05 16:46:42 CST 2016
    		Fri Aug 05 16:46:43 CST 2016
    		Fri Aug 05 16:46:44 CST 2016
    		Fri Aug 05 16:46:45 CST 2016
    
         */
    }
    
    package cn.lonecloud.test;
    
    import java.util.Date;
    import java.util.Timer;
    import java.util.TimerTask;
    
    public class Test01 {
    	public static void main(String[] args)throws Exception {
    		timer2();
    	}
    	/**
    	 * schedule
    	 * 线程休眠9s后执行
    	 * @Description: 
    	 * @throws Exception
    	 */
        public static void timer2() throws Exception {
        	Date date = new Date();
        	System.out.println(date);
            Timer timer = new Timer();
            Thread.sleep(9000);
            timer.schedule(new TimerTask() {
                public void run() {
    	                System.out.println(new Date());
                }
            }, date, 1000);
        }
        /**
         * 结果:
         *  Fri Aug 05 16:48:56 CST 2016
    		Fri Aug 05 16:49:05 CST 2016
    		Fri Aug 05 16:49:06 CST 2016
    		Fri Aug 05 16:49:07 CST 2016
    		Fri Aug 05 16:49:08 CST 2016
    		Fri Aug 05 16:49:09 CST 2016
    		Fri Aug 05 16:49:10 CST 2016
         */
    }
    
  • 相关阅读:
    剑指offer 找出数组中重复的数字
    SE知识整理——泛型
    Centos7 切换与安装图形界面
    laravel8 elasticsearch 配置搭建使用
    ts运行配置.md
    ts类型保护
    2022年4月工作资料
    Cmake使用
    关于线性筛的研究
    SkyWalking在.NET平台的简单使用
  • 原文地址:https://www.cnblogs.com/lonecloud/p/5742025.html
Copyright © 2020-2023  润新知