import java.util.Date; import java.util.concurrent.Phaser; import java.util.concurrent.TimeUnit; import static java.lang.Thread.currentThread; import static java.util.concurrent.ThreadLocalRandom.current; /** * @desc 重写Phaser 中的 onAdvance() 方法 **/ public class PhaserExample2 { public static void main(String[] args) { // 使用我们自定义的 Phaser , 并且在构造时传入回调函数 final Phaser phaser = new MyPhaser(()-> { System.out.println(new Date( ) + " :all of sub task completed work."); }); for (int i = 0; i < 10; i++) { new Thread(()-> { phaser.register(); try { TimeUnit.SECONDS.sleep(current().nextInt(20)); phaser.arriveAndAwaitAdvance(); System.out.println(new Date() + ":" + currentThread() + " completed the work."); } catch (InterruptedException e) { e.printStackTrace(); } },"T-"+i).start(); } } // 继承 Phaser private static class MyPhaser extends Phaser { private final Runnable runnable; private MyPhaser(Runnable runnable) { super(); this.runnable = runnable; } // 重写 onAdvance() 方法,当 parties 个任务都到达某个 phase 时该方法将被调用执行 @Override protected boolean onAdvance(int phase, int registeredParties) { this.runnable.run(); return super.onAdvance(phase,registeredParties); } } }
Phaser---重写Phaser 中的 onAdvance() 方法
最新推荐文章于 2021-02-15 15:42:44 发布