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

时间:2019-03-29 13:19:04

标签: java scheduled-tasks threadpoolexecutor

我正在安排有特定延迟的任务来处理我的物品:

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

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

1 个答案:

答案 0 :(得分:1)

您可以使用 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;
}