练习题之CyclicBarrier与CountDownLatch

一、CyclicBarrier使用

  new Thread().start();

  new Thread(new Runnable() {},"XXX").start();

public class CyclicBarrierTest {
 
  public static int NUM=10;

  public static void main(String[] args) {
   CyclicBarrier cyc = new CyclicBarrier(10);
   for(int i=0;i<NUM;i++) {
     new Thread(new Runnable() {
          public void run() {
             System.out.println(Thread.currentThread().getName() +":before CyclicBarrier");
             cyc.await();
             System.out.println(Thread.currentThread().getName() +":over CyclicBarrier");
          }
     },Thread.currentThread().getname()).start();
   }
  System.out.println("Test");
  }
}

 输出结果如下:

main:before CyclicBarrier
main:before CyclicBarrier
main:before CyclicBarrier
main:before CyclicBarrier
main:before CyclicBarrier
main:before CyclicBarrier
main:before CyclicBarrier
main:before CyclicBarrier
Test
main:before CyclicBarrier
main:over CyclicBarrier
main:over CyclicBarrier
main:over CyclicBarrier
main:over CyclicBarrier
main:over CyclicBarrier
main:over CyclicBarrier
main:over CyclicBarrier
main:over CyclicBarrier
main:over CyclicBarrier
main:over CyclicBarrier

二、CountDownLatch使用

public class CountDownTest {
   public static int NUM=10;
  
   public static void main(String[] args) {
      CountDownLatch latch = new CountDownLatch(NUM);
      for(int i =0;i<NUM;i++) {
        new Thread(new Runnable() {
           public void run() {
            System.out.println(Thread.currentThread.getName() + "Before CountDownLatch");
            latch.countDown();
            System.out.println(Thread.currentThread.getName() + "Over CountDownLatch");

            }
        },Thread.currentThread.geName()).start();
      }
      latch.await();
      System.out.println("Test");
   }
}

输出结果如下:

main:Before CountDownLatch
main:Before CountDownLatch
main:Over CountDownLatch
main:Before CountDownLatch
...
Test

 

posted @ 2016-04-17 09:37  moonandstar08  阅读(243)  评论(0编辑  收藏  举报