java定時器schedule和scheduleAtFixedRate區別

lonecloud發表於2016-08-05
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
     */
}

 

相關文章