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
*/
}
上一篇:SpringMVC通过注解获得参数


下一篇:六星经典CSAPP-笔记(7)加载与链接(上)