1

Is there any way I could control the order in which threads should resume its work after cyclic barrier "Barrier Action" has been completed?

Following is an example which I tried but order of final 2 statements keep changing but I don't want that to happen.It should always be:-

Thread 2 has crossed the barrier
Thread 1 has crossed the barrier

Code:-

public class CyclicBarrierExample {

    private static class Task1 implements Runnable {

        private CyclicBarrier barrier;

        public Task1(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
            } catch (InterruptedException | BrokenBarrierException ex) {
                System.out.println("Exception occured");
            }
        }
    }

    private static class Task2 implements Runnable {

        private CyclicBarrier barrier;

        public Task2(CyclicBarrier barrier) {
            this.barrier = barrier;
        }

        @Override
        public void run() {
            try {
                System.out.println(Thread.currentThread().getName() + " is waiting on barrier");
                barrier.await();
                System.out.println(Thread.currentThread().getName() + " has crossed the barrier");
            } catch (InterruptedException | BrokenBarrierException ex) {
                System.out.println("Exception occured");
            }
        }
    }

    public static void main(String args[]) throws InterruptedException {

        final CyclicBarrier cb = new CyclicBarrier(2, ()->{
                //This task will be executed once all thread reaches barrier
                System.out.println("All parties are arrived at barrier, lets play");
        });

        //starting each of thread
        Thread t1 = new Thread(new Task1(cb), "Thread 1");
        Thread t2 = new Thread(new Task2(cb), "Thread 2");

        t1.start();
        t2.start();

    }
}

Output:-

Thread 1 is waiting on barrier
Thread 2 is waiting on barrier
All parties are arrived at barrier, lets play
Thread 2 has crossed the barrier
Thread 1 has crossed the barrier
4

0 回答 0