Executorservice 等待任务完成后

Posted

技术标签:

【中文标题】Executorservice 等待任务完成后【英文标题】:Executorservice wait after tasks are finished 【发布时间】:2021-08-14 17:38:28 【问题描述】:

我有这段代码,它的作用是等待所有任务完成,然后才将值返回给小部件。 WorkerThread 是一个可运行对象,需要在下一个循环之前完成。

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 个任务的循环。

【问题讨论】:

【参考方案1】:

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


【讨论】:

以上是关于Executorservice 等待任务完成后的主要内容,如果未能解决你的问题,请参考以下文章

Java ExecutorService:等待终止所有递归创建的任务

ExecutorService

ExecutorService——shutdown方法和awaitTermination方法

ExecutorService的shutdown到底什么时候关闭

ExecutorService对象的shutdown 和shutdownNow 的区别

使用CompletionService结合ExecutorService批处理任务