線程併發工具--CountDownLatch

倒計時器,某個線程可以等待這個倒計時指向0的時候開始執行:

final CountDownLatch cdl = new CountDownLatch(10);
		for(int i = 0;i<10;i++){
			final int index = i;
			new Thread(new Runnable(){
				@Override
				public void run() {
					try {
						Thread.sleep(new Random().nextInt(5000));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("thread " + index + " execute complate!");
					cdl.countDown();
				}
			}).start();
		}
		System.out.println("main thread is awaiting...");
		try {
			cdl.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("all thread execute complate.");

主線程啓動10個線程開始來減少倒計時數量,等到減到0時主線程繼續執行,結果如下:

main thread is awaiting...
thread 0 execute complate!
thread 8 execute complate!
thread 2 execute complate!
thread 4 execute complate!
thread 9 execute complate!
thread 7 execute complate!
thread 5 execute complate!
thread 1 execute complate!
thread 6 execute complate!
thread 3 execute complate!
all thread execute complate.


發佈了61 篇原創文章 · 獲贊 9 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章