![](/img/trans.png)
[英]Java ScheduledExecutorService.scheduleWithFixedDelay starts new thread to execute the task without waiting for 1st task to complete
[英]ScheduledExecutorService wait for task to complete
我当前正在创建一个新线程,以检查文件夹中是否有新文件,然后在定义的时间内休眠。
我的首选是使用ScheduledExecutorService,但是我找不到任何文档来阐明该服务在开始新任务之前是否等待当前正在运行的任务完成。
例如,如果我有以下代码;
Integer samplingInterval = 30;
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10);
executorService.scheduleAtFixedRate(new WatchAgent(agentInfo), 0, samplingInterval, TimeUnit.SECONDS);
如果WatchAgent的run()花费的时间超过30秒,是否会在完成之前创建新的代理?
其次,如果创建WatchAgent的实例,是否可以在每次定期运行中继续使用相同的实例?
根据scheduleAtFixedRate的javadoc:
如果此任务的任何执行花费的时间超过其周期,则后续执行可能会开始得较晚,但不会同时执行。
根据定义, scheduleAtFixedRate
采用单个Runnable
实例。 您无法为每次run
调用提供不同的实例。 因此,为回答您的问题,每次定期运行将始终使用相同的实例。
请在下面尝试此测试代码。
1)是的,似乎要等到run()完成。
2)是的,似乎它正在使用同一个实例的run方法(您在调用scheduleAtFixedRate时传入的方法;顺便说一句,这很合理)。
import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class Test006 {
public static void main(String[] args) {
Object agentInfo = null;
Integer samplingInterval = 30;
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10);
executorService.scheduleAtFixedRate(new WatchAgent(agentInfo), 0, samplingInterval, TimeUnit.SECONDS);
}
}
class WatchAgent implements Runnable {
public WatchAgent(Object info){
}
public void run(){
try{
System.out.println("Running " + this.hashCode() + " - started on/at " + (new Date()));
Thread.sleep(60000);
System.out.println("Running " + this.hashCode() + " - finished on/at " + (new Date()));
}catch(Exception ex){
ex.printStackTrace();
}
}
}
输出:
Running 1322575120 - started on/at Mon Jul 08 19:58:41 IST 2019
Running 1322575120 - finished on/at Mon Jul 08 19:59:41 IST 2019
Running 1322575120 - started on/at Mon Jul 08 19:59:41 IST 2019
Running 1322575120 - finished on/at Mon Jul 08 20:00:41 IST 2019
Running 1322575120 - started on/at Mon Jul 08 20:00:41 IST 2019
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.