并发编程(CountDownLatch使用)

一.简介:

  Latch意思是:门闩的意思,形象的来说await就是拴上门闩,等到门闩释放后当前线程开始工作。

下面是来自简书上的解释:

  CountDownlatch是一个多功能的同步工具,可以被用于各种目的。一个CountDownLatch通过一个值为1的count被初始化,来作为一个开/关的门或门闩:所有调用了await()的线程都会在门前等待,直到门被一个线程通过调用countDown()打开。一个被初始化为N的CountDownLatch可以被用来“在N个线程都完成了某种操作(或者一些操作已经被完成了N次)之后创建一个线程”。

CountDownLatch一个有用的属性就是它不需要线程们在继续执行之前,调用countDown来等待count被减到0。它简单地阻止了任何调用了await()的线程继续,直到所有的线程都能够通过。 

二.实例:
  两个线程各自执行100次,对i加1,等待两个线程结束输出i值。
  
import java.util.concurrent.CountDownLatch;

/**
 * Created by cuijunyong on 2018/2/3.
 */
public class Xunhuan {
  public static int i = 0;
  private static final CountDownLatch end = new CountDownLatch(2);
  private static final CountDownLatch start = new CountDownLatch(1);
  public static void main(String[] args) throws Exception{

    A a = new A();
//    A b = new A();
    MyThread myThread = new MyThread();
    Thread b = new Thread(myThread);
//    Thread[] threads = new Thread[10];
//    for(int x = 0; x < threads.length; x++){
//      threads[i] = new Thread(myThread);
//      threads[i].start();
//    }
    a.start();
    b.start();
    System.out.println("开始工作了
");
    start.countDown();
    end.await();
    System.out.println("a:" + a.isAlive());
    System.out.println("b:" +b.isAlive());
    System.out.println("i=" + i);
  }

  static class MyThread implements Runnable{


    public void run() {
//      int i = 0;
      try {
        start.await();
        int j = 0;
        while (j < 100){
          j++;
          i++;

          System.out.println("B = " + i);

        }
        System.out.println("end.count = " + end.getCount());
        end.countDown();

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  static class A extends Thread{
    @Override
    public void run() {
//      int i = 0;
      try {
        start.await();
        int j = 0;
        while (j < 100){
          j++;
          i++;
          System.out.println("A = " + i);
        }
        System.out.println("end.count = " + end.getCount());
        end.countDown();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

}

结果:前面略略略

A = 190
A = 191
A = 192
A = 193
A = 194
A = 195
B = 171
end.count = 2
B = 196
B = 197
B = 198
B = 199
B = 200
end.count = 1
a:false
b:false
i=200
原文地址:https://www.cnblogs.com/handsomecui/p/8469077.html