I recently went through this question on Stackoverflow, where problem is to print even and odd in two threads, in such a manner that they are printed in incremental order. The question is here, where I have provided one solution. This led me to think, what should we do, if we need N Threads to take turn in cyclical manner, in a predefined order ? I tried using CyclicBarrier for this. This is my code :
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
public class NThreadTurnTaking {
public static void main(String[] args) {
NThreadTurnTaking nThreadTurnTaking = new NThreadTurnTaking();
CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
NThreadTurnTaking.A a = nThreadTurnTaking.new A(cyclicBarrier);
NThreadTurnTaking.B b = nThreadTurnTaking.new B(cyclicBarrier);
NThreadTurnTaking.C c = nThreadTurnTaking.new C(cyclicBarrier);
Thread t1 = new Thread(a);
Thread t2 = new Thread(b);
Thread t3 = new Thread(c);
t1.start();
t2.start();
t3.start();
}
class A implements Runnable{
private final CyclicBarrier cyclicBarrier;
public A(CyclicBarrier cyclicBarrier) {
super();
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("A");
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
class B implements Runnable{
private final CyclicBarrier cyclicBarrier;
public B(CyclicBarrier cyclicBarrier) {
super();
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("B");
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
class C implements Runnable{
private final CyclicBarrier cyclicBarrier;
public C(CyclicBarrier cyclicBarrier) {
super();
this.cyclicBarrier = cyclicBarrier;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("C");
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
}
}
I want my program to print A->B->C in order. While using a CyclicBarrier does ensure that they are printed one after another, but the order is not being maintained, which is obvious, because I am not doing anything particular to tell my program that I want a specific order. This is the output :
B C A A C B B A C.....
So, how do we ensure order here ? Kindly help.