【TX】Timer工具天生有两大缺陷:
1:管理并发任务的缺陷;
Timer有且只有一个后台线程对任务进行调度,所以它并不支持并发任务的调度。因此如果存在多个任务,且任务时间过长,超过了两个任务的间隔时间,会导致执行效果和预期不符合。这从它的源码可以看出其是一个单线程的。
public class Timer {
private TaskQueue queue = new TaskQueue();
private TimerThread thread = new TimerThread(queue);
2:当任务抛出异常时的缺陷:
Timer对RuntimeException的支持力度不够,所以当抛出RuntimeException,Timer会停止所有任务的运行。
例1:并发缺陷
public class TimerTest extends TimerTask {
private String name;
private long costTime;
public TimerTest(String name, long costTime) {
super();
this.name = name;
this.costTime = costTime;
}
@Override
public void run() {
System.out.println(this.name+"开始时间:"+getTime());
try {
Thread.sleep(costTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(this.name+"结束时间:"+getTime());
}
public static String getTime(){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String format = sdf.format(new Date());
return format;
}
执行:
Timer time=new Timer();
TimerTest tA=new TimerTest("A程序", 2000);
TimerTest tB=new TimerTest("B程序", 2000);
tA.run();
tB.run();
time.schedule(tB, 1000*2,1000*1);
time.schedule(tA, 1000*2,1000*1);
结果:
A程序开始时间:2018-03-25 22:24:13
A程序结束时间:2018-03-25 22:24:15
B程序开始时间:2018-03-25 22:24:15
B程序结束时间:2018-03-25 22:24:17
B程序开始时间:2018-03-25 22:24:19
未完待续..........