(转)ScheduledExecutorService接口

来源:互联网 发布:燕山大学网络教学平台 编辑:程序博客网 时间:2024/05/01 20:55
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:关闭服务。