Java loopback barrier how to check?

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
{

    /**
     * @param args
     */
    public static void main(String[] args)
    {
        // ******************************************************************
        // Using CyclicBarrier to make all threads wait at a point until all
        // threads reach there
        // ******************************************************************
        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");

            // Do Something in the Thread
            Thread.sleep(1000*(int)(4*Math.random()*10));


            // Now Wait till all the thread reaches this point
            barrier.await();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        //Now do whatever else after all threads are released
        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 , ?, , , .

+5
3

, System.out . run():

        long id = Thread.currentThread().getId();
        System.out.println("I am thread " + id + " and I am waiting for my friends to arrive");
        // Do Something in the Thread
        Thread.sleep(1000*8);

, , .

+2

,

Thread.sleep(1000*(int)(8*Math.rand()));
+2

, 4 , "" "release..hurray". , , .

, , , . , , , ; , , , System.out.println.

Edit: A different sleep response for random times will help to better understand the concept of the barrier, since it will be (to some extent) the possibility of multiple flows arriving at the barrier at different points in time.

+1
source

All Articles