0
0

More than 1 year has passed since last update.

CyclicBarrier class

Last updated at Posted at 2023-01-23

指定した数のスレッドが終了したら、終了後メソッドを実行させるコントローラ
await methodが終了通知

疑問点
newFixedThreadPool(2),CyclicBarrier(3,...)にすると、
2個目の処理までは行われ、3個目の処理が動き出さない事象が
確認している。
CyclicBarrierに使用しているthread poolは占有されていて使いまわしが
できない?

また、CyclicBarrier(3,...)、実行するスレッドが7の場合、
shutdownしても実行終了しない。
CyclicBarrierが残りのスレッド要求を待ち続けているようだ。
強制的に終了させる方法が不明

class RunnableWithCyclicBarrier implements Runnable {
    private CyclicBarrier c;
    RunnableWithCyclicBarrier(CyclicBarrier c) {
        super();
        this.c = c;
    }
    @Override
    public void run() {
        long id = Thread.currentThread().getId();
        int i = new Random().nextInt(10) * 100;
        System.out.println("START" + id);
        try {
            Thread.sleep(i); 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("END" + id);
        try {
            this.c.await();
        } catch (InterruptedException ex) {
            Logger.getLogger(RunnableWithCyclicBarrier.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BrokenBarrierException ex) {
            Logger.getLogger(RunnableWithCyclicBarrier.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
public class Outer {
    public static void main(String[] args) {
        CyclicBarrier c = new CyclicBarrier(3, () -> {System.out.println("after method");});
        ExecutorService e = Executors.newFixedThreadPool(4);
        for(int i=0; i<3; i++) {
            RunnableWithCyclicBarrier r = new RunnableWithCyclicBarrier(c);
            e.submit(r);
            //e.shutdown();
        }
        e.shutdown();
    }
}
START15
START14
START13
END15
END14
END13
after method
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0