java路障CyclicBarrier

Posted 风的低吟

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java路障CyclicBarrier相关的知识,希望对你有一定的参考价值。

当所有线程都执行到某行代码,才可已往下执行:

package threadLock;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CyclicBarrierTest {

    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
        final CyclicBarrier barrier = new CyclicBarrier(3);
        for(int i = 0; i < 3; ++i){
            Runnable runnable  = new Runnable() {
                
                @Override
                public void run() {
                    
                        try {
                            Thread.sleep(new Random().nextInt(1000));
                            System.out.println("线程 " + Thread.currentThread().getName() + "即将到达目的地 1,当前已有" + (barrier.getNumberWaiting() + 1) + "个到达," + (barrier.getNumberWaiting() == 2 ? "继续走啊" : "") );
                            barrier.await();
                            Thread.sleep(new Random().nextInt(1000));
                            System.out.println("线程 " + Thread.currentThread().getName() + "即将到达目的地 2,当前已有" + (barrier.getNumberWaiting() + 1) + "个到达," + (barrier.getNumberWaiting() == 2 ? "继续走啊" : "") );
                            barrier.await();
                            Thread.sleep(new Random().nextInt(1000));
                            System.out.println("线程 " + Thread.currentThread().getName() + "即将到达目的地 3,当前已有" + (barrier.getNumberWaiting() + 1) + "个到达," + (barrier.getNumberWaiting() == 2 ? "继续走啊" : "") );
                            barrier.await();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        } catch (BrokenBarrierException e) {
                            e.printStackTrace();
                        }
                    }
                    
                
            };
            service.execute(runnable);
        }
    }
}

 

以上是关于java路障CyclicBarrier的主要内容,如果未能解决你的问题,请参考以下文章

Java的CountDownLatch和CyclicBarrier的理解和区别

java CyclicBarrier的介绍和使用

java.util.concurrent常用类(CountDownLatch,Semaphore,CyclicBarrier,Future)

Java CyclicBarrier

P2176路障与P1186玛丽卡与P1491集合位置全面胜利

java CyclicBarrier“ count”字段未使用final定义。如何确保计数字段的安全发布