I am getting ready for an interview and just want to prepare some basic examples and flow patterns so that I can use them during my white encoding, if necessary.
I read about CyclicBarrier and just tried my hands, so I wrote very simple code:
import java.util.concurrent.CyclicBarrier;
public class Threads
{
public static void main(String[] args)
{
barrier = new CyclicBarrier(N);
for (int i = 0; i < N; ++i)
{
new Thread(new CyclicBarrierWorker()).start();
}
}
static class CyclicBarrierWorker implements Runnable
{
public void run()
{
try
{
long id = Thread.currentThread().getId();
System.out.println("I am thread " + id + " and I am waiting for my friends to arrive");
Thread.sleep(1000*(int)(4*Math.random()*10));
barrier.await();
}
catch (Exception e)
{
e.printStackTrace();
}
long id1 = Thread.currentThread().getId();
System.out.println("Thread:"+id1+" We all got released ..hurray!!");
System.out.println("We all got released ..hurray!!");
}
}
final static int N = 4;
static CyclicBarrier barrier = null;
}
You can copy it as is and run it in your compiler.
What I want to check is that currently all threads are waiting for code:
barrier.await();
I placed some expectation and hoped that I would see 4 statements appear one after another sequentially on the console, and then "outburst" from the "release..hurray" report. But I see a splash of all statements together no matter what I choose as a dream.
Did I miss something?
P.S: -, http://codepad.org/F01xIhLl, Java , ?, , , .