循环屏障完成其操作后的线程控制顺序?

时间:2019-07-11 05:06:26

标签: java multithreading cyclicbarrier

有什么方法可以控制循环屏障“屏障行动”完成后线程恢复工作的顺序?

以下是我尝试的示例,但最后2条语句的顺序不断变化,但我不希望发生这种情况,它应该始终是:-

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

代码:-

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();

    }
}

输出:-

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

0 个答案:

没有答案