併發編程(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
相關文章
相關標籤/搜索