美文网首页
CyclicBarrier用法

CyclicBarrier用法

作者: jsjack_wang | 来源:发表于2018-01-23 14:58 被阅读0次
    1.简介
        通俗点讲就是一组线程相互等待,直到临界点。具体可查官方文档
        注意:CountDownLatch是一组线程或一个线程等待另一组线程
    
    2.小栗子
    public class CyclicBarrierDemo {
    
        private static final int CYCLIC_BARRIER_COUNT = 2;
        private static final int THREAD_COUNT = 4;
    
        public static void main(String[] args) {
            CyclicBarrier cyclicBarrier = new CyclicBarrier(CYCLIC_BARRIER_COUNT, ()->{
                System.out.println("达到临界点");
            });
    
            ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);
            for (int index = 0; index < THREAD_COUNT; index ++) {
                executorService.execute(()->{
                    try {
                        System.out.println("ThreadId:" + Thread.currentThread().getId());
                        Thread.sleep(2000);
                        int await = cyclicBarrier.await();
                        System.out.println("await:" + await);
                        System.out.println("ThreadId:" + Thread.currentThread().getId());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            }
            executorService.shutdown();
        }
    }

    相关文章

      网友评论

          本文标题:CyclicBarrier用法

          本文链接:https://www.haomeiwen.com/subject/lvusaxtx.html