I want to implement a custom java barrier. I don’t want to use the CyclicBarrier class.
So all threads meet at a common point. The threads only procceed if all threads arrived at the barrier.
I want to use the wait/notify/notifyAll methods to implement the barrier.
So this is what I came up with
public class Barrier{
private final int threadNumber;
public Barrier(int pThreadNumber){
this.threadNumber = pThreadNumber;
}
public synchronized void barrier(){
wait();
}
public synchronized void releaseBarrier(){
notifyAll();
}
public synchronized void releaseThread(){
notify();
}
}
But I don’t really understand how to achieve that a certain number of threads are stopped until all threads arrived. Is it possible to implement a barrier using only wait/notify/notify all?
Sort of homework, so I am only giving a hint:
You want all threads to proceed when
threadNumberthreads are waiting. That’s equivalent to the firstthreadNumber - 1threads waiting for thethreadNumber-th thread to arrive. One way is to count the number of threads, and do something special once thethreadNumber-th thread arrives.