2

Recently I learned CyclicBarrier, but here's a question:

Code:

public class Main {
    public static CyclicBarrier c;

    public static void main(String[] agrs){
        int threadsCount = 5;
        c = new CyclicBarrier(threadsCount + 1);
        // make 5 A threads to run
    }
}

public class A implements Runnable {

    public void run(){
        // do something
       Main.c.await();
        // do something
    }
}

In about code, I wonder that why I must initialize CyclicBarrier by (threadsCount + 1) but not (threadsCount), since I never invoke await() in the main method?

Shekhar_Pro
  • 18,056
  • 9
  • 55
  • 79
Hesey
  • 4,957
  • 6
  • 31
  • 31
  • You mustn't. If you run `threadsCount` threads, your code won't work because the number of Threads calling `await()` must be *equal* to the number of parties in the CyclicBarrier! You must be doing something wrong in the code you omitted. BTW: You did ask the [same question](http://stackoverflow.com/questions/5201274/why-use-cyclicbarrierthreads-1) yesterday, why was that deleted? – Boris Mar 06 '11 at 08:01

2 Answers2

0

n is the number of parties where new CyclicBarrier(n) creates a new CyclicBarrier that will trip when the given number of parties (threads) are waiting upon it, and does not perform a predefined action upon each barrier.

I would posit that the origin thread is counted as accessing the barrier, thus when you create 5 new threads, if you didn't wait on 5+1 threads then you'd trip before you were ready.

Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
0

You must specify the exact number of parties that will wait on the CyclicBarrier, if you specify n+1, then you will have to have n+1 threads invoke wait on the CyclicBarrier in order for it to trip.

Kiril
  • 39,672
  • 31
  • 167
  • 226