您的位置:首页 > 其它

ScheduledExecutorService和timer的异同

2014-08-18 19:15 411 查看
先来个传统的Timer的例子:

[java]
view plaincopy

package com.jerry.concurrency;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TraditionalTask {


public static void main(String[] args) throws ParseException {
Timer myTimer = new Timer();
myTimer.schedule(new Worker(), 1000);//1秒后执行
// 2012-02-28 09:58:00执行
myTimer.schedule(new Worker(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-02-28 09:58:00"));
myTimer.schedule(new Worker(), 5000,1000);//5秒后执行 每一秒执行一次
// 2012-02-28 09:58:00执行一次 以后每秒执行一次,如果设定的时间点在当前时间之前,任务会被马上执行,然后开始按照设定的周期定时执行任务
myTimer.schedule(new Worker(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-02-28 09:58:00"),1000);
myTimer.scheduleAtFixedRate(new Worker(), 5000,1000);//5秒后执行 每一秒执行一次 如果该任务因为某些原因(例如垃圾收集)而延迟执行,那么接下来的任务会尽可能的快速执行,以赶上特定的时间点
myTimer.scheduleAtFixedRate(new Worker(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2012-02-28 09:58:00"),1000);//和上个类似
}
}


class Worker extends TimerTask {

@Override
public void run() {

System.out.println("我被执行了!"+"时间是:"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}

}

传统的timer的缺点:Timer对任务的调度是基于绝对时间的;所有的TimerTask只有一个线程TimerThread来执行,因此同一时刻只有一个TimerTask在执行;任何一个TimerTask的执行异常都会导致Timer终止所有任务;由于基于绝对时间并且是单线程执行,因此在多个任务调度时,长时间执行的任务被执行后有可能导致短时间任务快速在短时间内被执行多次或者干脆丢弃多个任务。
ScheduledExecutorService克服了上述缺点,例子如下:

[java]
view plaincopy

<span style="font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;font-size:13px;">package com.jerry.concurrency;


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;




public class TestScheduledExecutorService{
public static void main(String[] args) throws Exception{
ScheduledExecutorService execService = Executors.newScheduledThreadPool(3);
// 5秒后开始执行 每个2秒执行一次,如果有的任务执行要花费比其周期更长的时间,则将推迟后续执行,但不会同时执行
// 每次相隔相同的时间执行任务,如果任务的执行时间比周期还长,那么下一个任务将立即执行
execService.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println("任务:"+Thread.currentThread().getName()+" 执行了,时间为: "+System.currentTimeMillis());
try {
Thread.sleep(1000L);
} catch (Exception e) {
e.printStackTrace();
}
}
}, 5, 2, TimeUnit.SECONDS);
//5秒后开始执行 每个2秒执行一次,保证固定的延迟为2秒 下一个任务的开始时间与上一个任务的结束时间间隔相同
execService.scheduleWithFixedDelay(new Runnable() {
public void run() {
System.out.println("任务:"+Thread.currentThread().getName()+"执行了,时间为:"+System.currentTimeMillis());
try {
Thread.sleep(1000L);
} catch (Exception e) {
e.printStackTrace();
}
}
}, 5, 2, TimeUnit.SECONDS);
Thread.sleep(10000L);
execService.shutdown();
}
}
</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: