schedule方法和scheduleAtFixedRate方法的区别

schedulescheduleAtFixedRate方法都可以实现任务的延时和不延时执行且都会按顺序执行,因此不需要考虑非线程安全的情况。它们的主要区别只在于有没有追赶特性。其中,schedule方法不具有追赶特性,而scheduleAtFixedRate方法具有追赶特性。

首先验证schedule方法不具有追赶执行性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class App {
public static void main( String[] args ) {
MyTask myTask = new MyTask();
System.out.println("当前执行时间为: " + new Date());
Calendar c = Calendar.getInstance();
c.set(Calendar.SECOND, c.get(Calendar.SECOND) - 5);
Date runDate = c.getTime();
System.out.println("计划执行时间为: " + runDate);
Timer timer = new Timer();
//调用的是schedule方法,验证其不具追赶性
timer.schedule(myTask, runDate, 1000);
}
}

class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("time = " + new Date());
}
}

运行结果

1
2
3
4
5
6
7
8
9
10
当前执行时间为: Sat Apr 06 17:56:50 CST 2017
计划执行时间为: Sat Apr 06 17:56:45 CST 2017
time = Sat Apr 06 17:56:50 CST 2017
time = Sat Apr 06 17:56:51 CST 2017
time = Sat Apr 06 17:56:52 CST 2017
time = Sat Apr 06 17:56:53 CST 2017
time = Sat Apr 06 17:56:54 CST 2017
time = Sat Apr 06 17:56:55 CST 2017
time = Sat Apr 06 17:56:56 CST 2017
time = Sat Apr 06 17:56:57 CST 2017

时间Sat Apr 06 17:56:45 CST 2017Sat Apr 06 17:56:50 CST 2017之间的时间所对应的Task任务就被取消掉,不被执行了,这就是Task任务不追赶。

验证scheduleAtFixedRate方法具有追赶执行性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class App {
public static void main( String[] args ) {
MyTask myTask = new MyTask();
System.out.println("当前执行时间为: " + new Date());
Calendar c = Calendar.getInstance();
c.set(Calendar.SECOND, c.get(Calendar.SECOND) - 5);
Date runDate = c.getTime();
System.out.println("计划执行时间为: " + runDate);
Timer timer = new Timer();
//调用scheduleAtFixedRate方法,测试其具有追赶性
timer.scheduleAtFixedRate(myTask, runDate, 1000);
}
}

class MyTask extends TimerTask {
@Override
public void run() {
System.out.println("time = " + new Date());
}
}

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
当前执行时间为: Sat Apr 06 17:58:30 CST 2017
计划执行时间为: Sat Apr 06 17:58:25 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:30 CST 2017
time = Sat Apr 06 17:58:31 CST 2017
time = Sat Apr 06 17:58:32 CST 2017
time = Sat Apr 06 17:58:33 CST 2017
time = Sat Apr 06 17:58:34 CST 2017
time = Sat Apr 06 17:58:35 CST 2017
time = Sat Apr 06 17:58:36 CST 2017
time = Sat Apr 06 17:58:37 CST 2017

将两个时间段内所对应的Task任务被“补充性”地执行,这就是Task任务追赶特性。

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :