Java并发 专题
您的位置:java > Java并发专题 > Java并发ScheduledExecutorService接口
Java并发ScheduledExecutorService接口
作者:--    发布时间:2019-11-20

java.util.concurrent.scheduledexecutorservice接口是executorservice接口的子接口,并支持将来和/或定期执行任务。

scheduledexecutorservice接口的方法

序号 方法 描述
1 scheduledfuture schedule(callable callable, long delay, timeunit unit) 创建并执行在给定延迟后启用scheduledfuture
2 scheduledfuture<?> schedule(runnable command, long delay, timeunit unit) 创建并执行在给定延迟后启用的单次操作。
3 scheduledfuture<?> scheduleatfixedrate(runnable command, long initialdelay, long period, timeunit unit) 创建并执行在给定的初始延迟之后,随后以给定的时间段首先启用的周期性动作; 那就是执行会在initialdelay之后开始,然后是initialdelay + period,然后是initialdelay + 2 * period,等等。
4 scheduledfuture<?> schedulewithfixeddelay(runnable command, long initialdelay, long delay, timeunit unit) 创建并执行在给定的初始延迟之后首先启用的定期动作,随后在一个执行的终止和下一个执行的开始之间给定的延迟。

实例

以下testthread程序显示了基于线程的环境中scheduledexecutorservice接口的使用。

import java.util.concurrent.executors;
import java.util.concurrent.scheduledexecutorservice;
import java.util.concurrent.scheduledfuture;
import java.util.concurrent.timeunit;

public class testthread {

   public static void main(final string[] arguments) throws interruptedexception {
      final scheduledexecutorservice scheduler = executors.newscheduledthreadpool(1);

      final scheduledfuture<?> beephandler = 
         scheduler.scheduleatfixedrate(new beeptask(), 2, 2, timeunit.seconds);

      scheduler.schedule(new runnable() {
         @override
         public void run() {
            beephandler.cancel(true);
            scheduler.shutdown();            
         }
      }, 10, timeunit.seconds);
   }  

   static class beeptask implements runnable {
      public void run() {
         system.out.println("beep");      
      }
   }
}

这将产生以下结果 -

beep
beep
beep
beep
beep

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册