java定时任务之Timer和ScheduledExecutorService

java定时任务

timer

1、执行多个任务的时候,必须第一个执行完后才会执行第二个。

2、timer是单线程执行,因此一个任务抛异常,其它任务也不能执行了。

 import java.util.Timer;  
 import java.util.TimerTask;  
   
 public class TimerTest  
 {  
     private static long start;  
   
     public static void main(String[] args) throws Exception  
     {  
   
         TimerTask task1 = new TimerTask()  
         {  
             @Override  
             public void run()  
             {  
   
                 System.out.println("task1 invoked ! "  
                         + (System.currentTimeMillis() - start));  
                 try  
                 {  
                     Thread.sleep(3000);  
                 } catch (InterruptedException e)  
                 {  
                     e.printStackTrace();  
                 }  
   
             }  
         };  
         TimerTask task2 = new TimerTask()  
         {  
             @Override  
             public void run()  
             {  
                 System.out.println("task2 invoked ! "  
                         + (System.currentTimeMillis() - start));  
             }  
         };  
         Timer timer = new Timer();  
         start = System.currentTimeMillis();  
         timer.schedule(task1, 1000);  
         timer.schedule(task2, 3000);  
   
     }  
 }  

执行结果:

task1 invoked ! 1000

task2 invoked ! 4000

newScheduledThreadPool:

1、可以多个线程同时执行不同的任务。

2、因为是多个线程所有,任务抛出异常,不影响其它任务的执行。

  • scheduleAtFixedRate : 0s后开始执行任务,前一次任务的开始时间和下次任务的开始时间中间间隔是5s , 如果前一次任务执行时间大于5s ,那么下次任务会在队列种等待,直到前一次任务执行完后,再执行。
  • scheduleWithFixedDelay : 0s后开始执行任务,前一次任务的结束时间和后一次任务的开始时间中间间隔是5s。
public class Scheduled {
    static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
    static class Task implements Runnable {
        public void run() {
            try {
                Thread.sleep(2000L);
                System.out.println(Thread.currentThread().getName());
            } catch (Exception e) {

            }
        }
    }
    /**
     * command:执行线程
     * initialDelay:初始化延时
     * period:两次开始执行最小间隔时间
     * delay:前一次执行结束到下一次执行开始的间隔时间(间隔执行延迟时间)
     * unit:计时单位
     */
    public static void main(String[] args) {
        scheduledExecutorService.scheduleAtFixedRate(new Task(), 0L, 5000L, TimeUnit.MILLISECONDS);
        scheduledExecutorService.scheduleWithFixedDelay(new Task(), 0L, 5000L, TimeUnit.MILLISECONDS);
    }
}

转载于:https://www.cnblogs.com/DivineHost/p/8681533.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值