How do I get the java.concurrency.CyclicBarrier to work as expected
Posted
by Ritesh M Nayak
on Stack Overflow
See other posts from Stack Overflow
or by Ritesh M Nayak
Published on 2010-03-26T09:38:02Z
Indexed on
2010/03/26
9:43 UTC
Read the original article
Hit count: 464
I am writing code that will spawn two thread and then wait for them to sync up using the CyclicBarrier class. Problem is that the cyclic barrier isn't working as expected and the main thread doesnt wait for the individual threads to finish. Here's how my code looks:
class mythread extends Thread{
CyclicBarrier barrier;
public mythread(CyclicBarrier barrier) {
this.barrier = barrier;
}
public void run(){
barrier.await();
}
}
class MainClass{
public void spawnAndWait(){
CyclicBarrier barrier = new CyclicBarrier(2);
mythread thread1 = new mythread(barrier).start();
mythread thread2 = new mythread(barrier).start();
System.out.println("Should wait till both threads finish executing before printing this");
}
}
Any idea what I am doing wrong? Or is there a better way to write these barrier synchronization methods? Please help.
© Stack Overflow or respective owner