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



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

while (currentPosition < count) {
    ExtractItemsProcessor extractItemsProcessor = 
        getExtractItemsProcessor(currentPosition, currentPositionLogger);
    executor.schedule(extractItemsProcessor, waitBetweenProzesses, TimeUnit.SECONDS);
    waitBetweenProzesses += sleepTime;
    currentPosition += chunkSize;
}
例如,如何安排 3 个任务

(有一个具有 3 个线程的执行器(,并且每个线程在完成任务后必须等待 10 秒?

您可以使用返回 ExecutorService的 Executors.newFixedThreadPool(NB_THREADS(。然后使用此执行器服务,您可以提交任务。例:

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);
    }
}

它将并行运行 te 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;
}

最新更新