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

How to schedule concurrent Runnables according to number of threads whereas a thread has to wait a delay after completing the task

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

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) 其中 returns 一个 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;
}