ScheduledExecutorService等待任务完成

owe*_*n79 3 java scheduledexecutorservice

我当前正在创建一个新线程,以检查文件夹中是否有新文件,然后在定义的时间内休眠。

我的首选是使用ScheduledExecutorService,但是我找不到任何文档来阐明该服务在开始新任务之前是否等待当前正在运行的任务完成。

例如,如果我有以下代码;

Integer samplingInterval = 30;
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(10);
executorService.scheduleAtFixedRate(new WatchAgent(agentInfo), 0, samplingInterval, TimeUnit.SECONDS);
Run Code Online (Sandbox Code Playgroud)

如果WatchAgent的run()花费的时间超过30秒,是否会在完成之前创建新的代理?

其次,如果创建WatchAgent的实例,是否可以在每次定期运行中继续使用相同的实例?

Joh*_*n B 5

根据scheduleAtFixedRate的javadoc :

如果此任务的任何执行花费的时间超过其周期,则后续执行可能会开始得较晚,但不会同时执行。

scheduleAtFixedRate根据定义,它只包含一个Runnable实例。您无法为的每次调用提供不同的实例run。因此,为回答您的问题,每次定期运行都将始终使用相同的实例。