并发同步辅助器


CountDownLatch(减法计数器):

 1     /*
 2      * latch.countDown();数量减1,如果当前计数等于零,那么没有任何反应。释放所有等待的线程。
 3      * latch.await();计数到零执行下一步
 4      */
 5     @Test
 6     public void testCountDownLatch() throws InterruptedException {
 7         CountDownLatch latch = new CountDownLatch(6);
 8         for (int i = 0; i < 6; i++) {
 9             new Thread(() -> {
10                 System.out.println(Thread.currentThread().getName() + "Go out");
11                 latch.countDown();
12             }, String.valueOf(i)).start();
13         }
14 
15         latch.await();
16         System.out.println("close door");
17     }    
 

 


cyclicBarrier(加法计数器):
 1     @Test
 2     public void testCyclicBarrier(){
 3         CyclicBarrier barrier = new CyclicBarrier(7,()->{
 4             System.out.println("成功召唤神龙");
 5         });
 6         for (int i = 1; i <= 7; i++) {
 7             final int temp = i; 
 8             new Thread(() -> {
 9                 System.out.println(Thread.currentThread().getName() +"收集" + temp +"龙珠");
10                 try {
11                     barrier.await();
12                 } catch (InterruptedException e) {
13                     e.printStackTrace();
14                 } catch (BrokenBarrierException e) {
15                     e.printStackTrace();
16                 }
17             }).start();
18         }
19     }

 

 

 

 

posted @ 2020-08-22 13:22  cgfamily  阅读(95)  评论(0)    收藏  举报