Wait for completion of all tasks with Java Phaser

Problem

Producer wants to wait for completion of all tasks before proceeding.

Solution

Producer side

// Add producer as a party
Phaser phaser = new Phaser(1);

for (int i=0; i<10000; ++i) {
  // Add each task as a party
  phaser.register();
  queue.put(new Task());
}

// Producer arrived and wait for completion of all tasks
phaser.arriveAndAwaitAdvance();

// At the end, there is only 1 party left which is the producer itself

Enter fullscreen mode Exit fullscreen mode

Consumer side

while (true) {
  Task task = queue.take();
  processTask(task);
  // Task completed and remove itself as a party
  phaser.arriveAndDeregister();
}

Enter fullscreen mode Exit fullscreen mode

原文链接:Wait for completion of all tasks with Java Phaser

© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容