任务调度ScheduleExecutorService学习心得

来源:互联网 发布:.blog域名 编辑:程序博客网 时间:2024/06/03 07:33

在javaSE中有Timer类和ScheduledExecutorService 类,timer类是基于绝对时间,ScheduledExecutorService 是基于相对时间,绝对时间有个缺陷,如果用户修改了电脑的系统时间,可能会对程序造成影响,而相对时间不会发生这种问题,timer类是基于轮询机制,ScheduledExecutorService 是基于多线程,所以他们的内部结构也不相同。这里就不多讲了,有兴趣的可以百度。

public class FirstClass {

private static SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
public static void main(String[] args) {
first();
seconds();
}
static void first(){
ScheduledExecutorService st = Executors.newScheduledThreadPool(1);
st.scheduleAtFixedRate(new Runnable() {

@Override
public void run() {
System.out.println("time: "+format.format(new Date()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 1000, 5000, TimeUnit.MILLISECONDS);

}

static void seconds(){
ScheduledExecutorService st = Executors.newScheduledThreadPool(1);
st.scheduleWithFixedDelay(new Runnable() {

@Override
public void run() {
System.out.println("time: "+format.format(new Date()));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 1000, 5000, TimeUnit.MILLISECONDS);

}


}

scheduleAtFixedRate运行结果:

time: 2017-11-21 09:50:12:421
time: 2017-11-21 09:50:17:421
time: 2017-11-21 09:50:22:420
time: 2017-11-21 09:50:27:421
time: 2017-11-21 09:50:32:421

scheduleWithFixedDelay运行结果:

time: 2017-11-21 09:52:06:554
time: 2017-11-21 09:52:12:558
time: 2017-11-21 09:52:18:559
time: 2017-11-21 09:52:24:565
time: 2017-11-21 09:52:30:566

由第一个运行的结果可知scheduleAtFixedRate无论线程内部是否有等待事件,都不影响第二次执行,而scheduleWithFixedDelay会等待第一次线程结束才进行第二次线程,如果第一次发生了异常将会影响到后续的运行,所以如果使用scheduleWithFixedDelay需要对异常和可能发生的时间做出处理。