ExecutorService 在任务完成后等待

Executorservice wait after tasks are finished

我有这段代码,它的作用是等待所有任务完成,然后才将 return 值传递给小部件。 WorkerThread 是一个 runnable,需要在下一个循环之前完成。

final ScheduledExecutorService ecs = Executors.newScheduledThreadPool(size2/2);
while(size2>1) {
    for (int i = 0; i < size2/2; i++) {
        Runnable worker = null;
        try {
            worker = new WorkerThread(players.take(), players.take() ,area,players);
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        }
        ecs.submit(worker);
    }
    area.append("\n\n next Round");
    size2=size2/2;
}

所以我需要做的是在这种情况下完成 8 个任务,获取它们附加到小部件的值,然后等待 2 秒,然后继续循环,现在有 4 个任务。

您可以使用 Phaser.

Phaser phaser = new Phaser(1); // Create Phaser instance
final ScheduledExecutorService ecs = Executors.newScheduledThreadPool(size2/2);
while(size2>1) {
    for (int i = 0; i < size2/2; i++) {
        Runnable worker = null;
        try {
            worker = new WorkerThread(players.take(), players.take() ,area,players);
        } catch (InterruptedException interruptedException) {
            interruptedException.printStackTrace();
        }
        phaser.register(); // Register a party
        ecs.submit(worker);
    }
    phaser.arriveAndAwaitAdvance(); // Wait for completion of all tasks
    area.append("\n\n next Round");
    size2=size2/2;
}

这是您的消费者。

public class WorkerThread {

    public WorkerThread(Phaser phaser) {
        this.phaser = phaser;
    }

    public void run() {
        processThings();
        phaser.arriveAndDeregister(); // Deregister a party
    }

}