java併發之CountDownLatch

java.util.conccurent包中有不少關於併發中可能會使用到的工具類,本文的主角CountDownLatch就是其中之一,其實CountDownLatch就是一個計數器,在它的計數值變爲0以前,它的await方法會阻塞當前線程的執行。java

構造函數

CountDownLatch只有一個構造函數,這個函數接受一個int類型的參數,這個參數的意義就是計數器的計數值,若是你想在程序中得到一個CountDownLatch的實例,你能夠:併發

CountDownLatch countDownLatch = new CountDownLatch(1);

如何使用

import java.util.concurrent.CountDownLatch;

/**
 * Filename : Child.java
 * Created by Derekxyz on 2014/7/18.
 */
public class Child implements Runnable{

	private CountDownLatch c1;

	public Child(CountDownLatch c1) {
		this.c1 = c1;
	}

	public void run() {

		try {
			System.out.println("i`m child,i want to eat");
			c1.await();
			System.out.println("oh ,it`s very delicious!");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		CountDownLatch latch = new CountDownLatch(1);//實例化一計數值爲1的計數器
		Thread t = new Thread(new Child(latch));
		t.start();//會輸出i`m child,i want to eat,而後等待計數器的值歸零
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("now it`s time to eat");
		latch.countDown();//將計數值減一,即變爲0 

		//線程中的下一句話oh ,it`s very delicious!,此刻將會輸出。


	}
}

上面一段代碼簡單的介紹了CountDownLatch的使用方法。函數

相關文章
相關標籤/搜索