zoukankan      html  css  js  c++  java
  • 练习题之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
  • 相关阅读:
    NOIP2009 pj
    数星星(POJ2352 star)
    洛谷 p3372 模板-线段树 1
    Luogu P1198 [JSOI2008]最大数 线段树
    Bestcoder#92&HDU 6017 T3 Girl loves 233 DP
    NOIP2008pj & luoguP1058 立体图 模拟
    NOIP2003TG 加分二叉树 区间DP
    Redis Jedis lua脚本
    Mac Ideal 常用快捷键
    Mysql慢查询explain
  • 原文地址:https://www.cnblogs.com/moonandstar08/p/5400323.html
Copyright © 2011-2022 走看看