ScheduledExecutorService的使用

ScheduledExecutorService接口
在ExecutorService的基础上,ScheduledExecutorService提供了按时间安排执行任务的功能,它提供的方法主要有:
  • schedule(task,initDelay):安排所提交的Callable或Runnable任务在initDelay指定的时间后执行。
  • scheduleAtFixedRate():安排所提交的Runnable任务按指定的间隔重复执行
  • scheduleWithFixedDelay():安排所提交的Runnable任务在每次执行完后,等待delay所指定的时间后重复执行。
    代码:ScheduleExecutorService的例子
  • import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.Executors;
    import java.util.concurrent.ScheduledExecutorService;
    import java.util.concurrent.ScheduledFuture;
    import java.util.concurrent.TimeUnit;

    public class ScheduledExecutorServiceTest
    {
           public static void main(String[] args) throws InterruptedException,ExecutionException
           {
                  //*1
                   ScheduledExecutorService service=Executors.newScheduledThreadPool(2);
                   //*2
                   Runnable task1=new Runnable()
                   {
                        public void run()
                        {
                           System.out.println("Taskrepeating.");
                        }
                   };
                   //*3
                   final ScheduledFuture future1=service.scheduleAtFixedRate(task1,0,1,TimeUnit.SECONDS);
                   //*4
                   ScheduledFuture future2=service.schedule(new Callable()
                {
                        public String call()
                        {
                                future1.cancel(true);
                                return "taskcancelled!";
                        }
                   },10,TimeUnit.SECONDS);
                   System.out.println(future2.get());
         //*5
         service.shutdown();
       }
    }

  • 这个例子有两个任务,第一个任务每隔一秒打印一句“Taskrepeating”,第二个任务在5秒钟后取消第一个任务。

    *1:初始化一个ScheduledExecutorService对象,这个对象的线程池大小为2。
    *2:用内函数的方式定义了一个Runnable任务。
    *3:调用所定义的ScheduledExecutorService对象来执行任务,任务每秒执行一次。能重复执行的任务一定是 Runnable类型。注意我们可以用TimeUnit来制定时间单位,这也是Java5.0里新的特征,5.0以前的记时单位是微秒,现在可精确到奈秒。
    *4:调用ScheduledExecutorService对象来执行第二个任务,第二个任务所作的就是在5秒钟后取消第一个任务。

    *5:关闭服务。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值