gpt4 book ai didi

java - 如何根据线程数量调度并发Runnables,而线程完成任务后必须等待延迟

转载 作者:行者123 更新时间:2023-12-02 10:04:19 25 4
gpt4 key购买 nike

我正在安排具有特定延迟的任务来处理我的项目:

while (currentPosition < count) {
ExtractItemsProcessor extractItemsProcessor =
getExtractItemsProcessor(currentPosition, currentPositionLogger);
executor.schedule(extractItemsProcessor, waitBetweenProzesses, TimeUnit.SECONDS);
waitBetweenProzesses += sleepTime;
currentPosition += chunkSize;
}

我如何安排例如 3 个任务(具有 3 个线程的执行器),并且每个线程在完成其任务后必须等待 10 秒?

最佳答案

您可以使用 Executors.newFixedThreadPool(NB_THREADS) 来返回 ExecutorService。然后使用这个 executorService 您可以提交任务。示例:

private static final int NB_THREADS = 3;

public static void main(String[] args) {

ExecutorService executorService = Executors.newFixedThreadPool(NB_THREADS);

for (int i = 0; i < NB_THREADS; i++) {
final int nb = i + 1;
Runnable task = new Runnable() {
public void run() {
System.out.println("Task " + nb);
try {
TimeUnit.SECONDS.sleep(10);
System.out.println("Task " + nb + " terminated");
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Error during thread await " + e); // Logging framework should be here
}
}
};

executorService.submit(task);
}


executorService.shutdown();
try {
executorService.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Error during thread await " + e);
}
}

它将并行运行 3 个任务,输出如下所示:

Task 1
Task 3
Task 2
Task1 terminated
Task2 terminated
Task3 terminated

在你的情况下,你可以这样做:

ExecutorService executorService = Executors.newFixedThreadPool(NB_THREADS);
while (currentPosition < count) {
ExtractItemsProcessor extractItemsProcessor =
getExtractItemsProcessor(currentPosition, currentPositionLogger);
executorService.submit(extractItemsProcessor); // In processor you should add the sleep method
waitBetweenProzesses += sleepTime;
currentPosition += chunkSize;
}

关于java - 如何根据线程数量调度并发Runnables,而线程完成任务后必须等待延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55418327/

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