JAVA定时调度工具Timer的缺陷

【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
未完待续..........
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值