gpt4 book ai didi

java - 具有并发重叠任务的scheduleWithFixedDelay

转载 作者:行者123 更新时间:2023-12-01 04:32:46 25 4
gpt4 key购买 nike

我正在寻找 ScheduledExecutor 的变体,它允许任务以特定的时间间隔运行,而无需等待上一个任务完成。

给定下面的代码,有 12 行不同的输出,间隔为 5000ms。

给定执行间隔为 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.
}

最佳答案

试试这个

    ExecutorService ex = Executors.newFixedThreadPool(10);
for (;;) {
List<Future<?>> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<?> f = ex.submit(new Runnable() {
@Override
public void run() {
System.out.println("running poller " + new Date());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("5000 passed");
}
});
list.add(f);
}
for (Future<?> f : list) {
f.get();
}
}

关于java - 具有并发重叠任务的scheduleWithFixedDelay,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17779448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com