使用调度线程池执行“指定时间只执行一次”和“指定时间间隔执行”

 

ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1);

executorService.schedule(new TimerTask() {
   @Override
   public void run() {
      try {
         System.out.println(System.currentTimeMillis()+"=000");
         Thread.sleep(7000);
         System.out.println(System.currentTimeMillis()+"=111");
      } catch (InterruptedException e) {
         e.printStackTrace();
      }
  }
},2, TimeUnit.SECONDS);

executorService.scheduleAtFixedRate(new TimerTask() {
  @Override
  public void run() {
     try {
        System.out.println(System.currentTimeMillis()+"=111222333");
        Thread.sleep(2000);
        System.out.println(System.currentTimeMillis()+"=666777888");
     } catch (InterruptedException e) {
        e.printStackTrace();
     }
  }
}, 2 , 5,TimeUnit.SECONDS);

/*
1610610883095=000
1610610890095=111
1610610890095=111222333
1610610892095=666777888
1610610892095=111222333
1610610894096=666777888
1610610894096=111222333
1610610896096=666777888
...
*/

总结:

1.new ScheduledThreadPoolExecutor(1) 指定创建1个线程,那么当第一个线程执行完才会继续执行第二个线程。

2.schedule(Runnable command,long delay, TimeUnit unit); 指定delay时间后执行command线程,且只执行一次。

3.scheduleAtFixedRate(Runnable command,long initialDelay, long period, TimeUnit unit);指定initialDelay时间后执行command线程,且隔period时间后再次执行command线程。

 

补充说明scheduleAtFixedRatescheduleWithFixedDelay区别:

scheduleAtFixedRate(Runnable command,long initialDelay,long period,TimeUnit unit); 指定initialDelay时间后执行command线程,且隔 period 时间后再次执行command线程。
scheduleWithFixedDelay(Runnable command,long initialDelay,long delay,TimeUnit unit);指定initialDelay时间后执行command线程,且隔 command线程执行耗时+period 时间后再次执行command线程。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值