我正在寻找 ScheduledExecutor 的变体,它允许任务以特定间隔运行,而无需等待前一个任务完成。
给定下面的代码,每隔 5000 毫秒就有 12 行不同的输出。
给定 50 毫秒的执行间隔和 10 的线程池大小,我正在寻找一种解决方案,它在前 550 毫秒内有 10 个输出行,然后暂停,直到线程被释放并可以重用。
ScheduledExecutorService pollingExecutorService = Executors.newScheduledThreadPool(10);
final Runnable pollingTask = new Runnable() {
public void run() {
System.out.println("running poller " + DateTime.now().toString());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
System.out.println("5000 passed");
}
};
ScheduledFuture<?> pollingHandler =
pollingExecutorService.scheduleWithFixedDelay(pollingTask,
0,
50,
TimeUnit.MILLISECONDS);
//wait secondsIdleBeforeShutdown seconds
try {
Thread.sleep(1000*60);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}