java.util.concurrent.ScheduledExecutorService
是一个可以安排任务延迟执行的
ExecutorService
, 或者以固定的时间间隔重复执行。任务通过一个工作线程异步执行,而不是提交任务到ScheduledExecutorService的线程。
ScheduledExecutorService例子
下面是ScheduledExecutorService
例子:
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(5);
ScheduledFuture scheduledFuture =
scheduledExecutorService.schedule(new Callable() {
public Object call() throws Exception {
System.out.println("Executed!");
return "Called!";
}
},
5,
TimeUnit.SECONDS);
首先,创建一个容纳5个线程的.然后,创建了Callable
接口的一个匿名类作为参数提交到Callable
。
ScheduledExecutorService实现
既然ScheduledExecutorService
是个接口, ava.util.concurrent
包中的ScheduledExecutorService
的类实现了该接口:
- ScheduledThreadPoolExecutor
创建ScheduledExecutorService
创建 ScheduledExecutorService
取决于你用哪种实现,当然也可以Executors
的工厂方法创建ScheduledExecutorService
实例,下面是代码:
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
ScheduledExecutorService用法
一旦创建了 ScheduledExecutorService
,可以用下面方法
:
- schedule (Callable task, long delay, TimeUnit timeunit)
- schedule (Runnable task, long delay, TimeUnit timeunit)
- scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)
- scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)
下面一一讲解这些方法:
schedule (Callable task, long delay, TimeUnit timeunit)
这个方法安排给定得 Callable
延迟执行,这方法返回ScheduledFuture
,可以用于在任务未执行前取消任务或者当执行完了获取返回结果,下面是代码:
ScheduledExecutorService scheduledExecutorService =
Executors.newScheduledThreadPool(5);
ScheduledFuture scheduledFuture =
scheduledExecutorService.schedule(new Callable() {
public Object call() throws Exception {
System.out.println("Executed!");
return "Called!";
}
},
5,
TimeUnit.SECONDS);
System.out.println("result = " + scheduledFuture.get());
scheduledExecutorService.shutdown();
输出结果:
Executed!
result = Called!
schedule (Runnable task, long delay, TimeUnit timeunit)
这个方法类似于上面得方法,但是没有返回结果,所以任务完成 ScheduledFuture.get()
将返回null
。
scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)
这个方法安排任务间隔执行,任务首次在initialDelay
以后执行,然后每次间隔initialDelay执行。
如果任何一次抛异常,那么任务不再执行,如果没有异常,任务一直执行直到ScheduledExecutorService
关闭,如果当前线程执行时间很长,那么下一个任务要等到这个任务执行完成,在同一时间只执行一个任务。
scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)
这个方法和 scheduleAtFixedRate()
非常相似,只是时间段有不同的解释。
在scheduleAtFixedRate()方法中,周期被解释为从上一次执行开始到下一次执行开始之间的延迟。
然而,在这种方法中,周期被解释为上一次执行结束到下一次执行开始之间的延迟。因此,延迟是在完成执行之间,而不是在执行开始之间。
ScheduledExecutorService Shutdown
和 ExecutorService
一样
, 当任务执行完毕 ScheduledExecutorService
需要关闭,如果不关闭,一直在JVM中运行,尽管其他线程已经关闭。
关闭ScheduledExecutorService
用shutdown()
或者 shutdownNow()
方法,这两个方法是从ExecutorService
接口继承得, 可以查看前面文章 ExecutorService 中得Shutdown 。
参考:https://blog.csdn.net/cgsyck/article/details/107692471
http://tutorials.jenkov.com/java-util-concurrent/scheduledexecutorservice.html