CyclicBarrier Class
A cyclic barrier is a mechanism for (re)synchronizing multiple threads, designed to block a specified number of threads and only allow them to proceed synchronously after all of them have invoked its resynchronization method. In Java, this mechanism is represented by the CyclicBarrier
class. Upon instantiation, the number of threads to be resynchronized is specified. This thread synchronization mechanism is useful for parallelized iterative algorithms that require a synchronization step for threads before moving on to the next iteration of computation. It's important to note that invoking the await() method on the cyclic barrier can throw exceptions such as BrokenBarrierException or InterruptedException.
public class Task extends Thread {
private int id;
public Task(int id) {
this.id = id;
}
public void run() {
while (!solved) {
executeAlgorithmStep();
try {
// Resynchronizing threads for the next step of the algorithm.
Main.barrier.await();
} catch (BrokenBarrierException | InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static CyclicBarrier barrier;
public static void main(String[] args) {
int NUMBER_OF_THREADS = 4;
barrier = new CyclicBarrier(NUMBER_OF_THREADS);
Task[] t = new Task[NUMBER_OF_THREADS];
for (int i = 0; i < NUMBER_OF_THREADS; ++i) {
t[i] = new Task(id);
t[i].start();
}
for (int i = 0; i < NUMBER_OF_THREADS; ++i) {
try {
t[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}