并发编程(CountDownLatch使用)

一.简介:java

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

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

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

CountDownLatch一个有用的属性就是它不须要线程们在继续执行以前,调用countDown来等待count被减到0。它简单地阻止了任何调用了await()的线程继续,直到全部的线程都可以经过。 spa

二.实例:
  两个线程各自执行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("开始工做了\n");
    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
相关文章
相关标签/搜索