任务调度ScheduleExecutorService学习心得

在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需要对异常和可能发生的时间做出处理。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值