Java并发程序设计(1)传统多线程技术之定时器

时间:2022-08-09 00:15:49

1. 传统多线程技术

 

1.1. Timer

1.1.1. 定时器基本用法

 

创建定时器任务.

TimerTask  task = new TimerTask(){

 

@Override

public void run(){

System.out.println("running at thread " + Thread.currentThread().getName());

}

};

 

 

经过多少毫秒后执行定时器任务:

Timer  timer = new Timer();

timer.schedule( task, 1000*3);

 

 

经过3秒后执行定时器任务,以后每隔3秒执行1.

timer.schedule( task, 1000*3, 1000*3);

 

 

 

在指定的时间点开始执行定时器任务,以后每隔3秒执行1次。时间点是已经过去的时间时,立即执行1次定时器任务。

   

 Timer  timer = new Timer();

TimerTask  task = new TimerTask(){

@Override

public void run(){

System.out.println("OnTimer:" +new Date());

}

};

 

Date starttime = new Date(2017-1900,2,4,19,41,30);

System.out.println("now is " + new Date());

System.out.println("starttime:" + starttime);

timer.schedule( task, starttime, 1000*10);

 

 

运行结果:

now is Sat Mar 04 19:40:22 CST 2017

starttime:Sat Mar 04 19:41:30 CST 2017

OnTimer:Sat Mar 04 19:41:30 CST 2017

OnTimer:Sat Mar 04 19:41:40 CST 2017

OnTimer:Sat Mar 04 19:41:50 CST 2017

OnTimer:Sat Mar 04 19:42:00 CST 2017

OnTimer:Sat Mar 04 19:42:10 CST 2017

 

 

1.1.2. 两种调度方式的区别

 

如果开始时间点是过去很久的时间,schedule仅仅立即执行1次,而不会立即把过去的时间中当做间隔时间来执行多次定时器任务。

 

Timer  timer = new Timer();

TimerTask  task = new TimerTask(){

@Override

public void run(){

System.out.println("OnTimer:" +new Date());

}

};

 

Date starttime = new Date(2017-1900,2,4,16,41,30);

System.out.println("now is " + new Date());

System.out.println("starttime:" + starttime);

timer.schedule( task, starttime, 1000*10);

 

 

now is Sat Mar 04 19:56:01 CST 2017

starttime:Sat Mar 04 16:41:30 CST 2017

OnTimer:Sat Mar 04 19:56:01 CST 2017

OnTimer:Sat Mar 04 19:56:11 CST 2017

OnTimer:Sat Mar 04 19:56:21 CST 2017

OnTimer:Sat Mar 04 19:56:31 CST 2017

 

 

scheduleAtFixedRate会将已经过去的时间纳入间隔时间的计算。如果开始时间点是过去很久的时间点,则会立即执行很多次。

timer.scheduleAtFixedRate( task, starttime, 1000*10);

 

 

now is Sat Mar 04 20:00:18 CST 2017

starttime:Sat Mar 04 16:41:30 CST 2017

OnTimer:Sat Mar 04 20:00:18 CST 2017

OnTimer:Sat Mar 04 20:00:18 CST 2017

OnTimer:Sat Mar 04 20:00:18 CST 2017

OnTimer:Sat Mar 04 20:00:18 CST 2017