CountDownLatch的簡單使用

個人理解就是當指定數量的線程全部執行完畢後再進行下一步動作

package study;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Test {
	public static class myThread extends Thread {
		int sleepSeconds;
		CountDownLatch countDownLatch;
		public myThread(String name,int seconds,CountDownLatch countDownLatch) {
			this.setName(name);
			this.sleepSeconds = seconds;
			this.countDownLatch = countDownLatch;
		}
		@Override
		public void run() {
			long startTime = System.currentTimeMillis();
			System.out.println(this.getName() + "開始執行");
			try {
				TimeUnit.SECONDS.sleep(sleepSeconds);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				countDownLatch.countDown();
			}
			
			long endTime = System.currentTimeMillis();
			System.out.println(this.getName() + "結束執行,耗時:" + String.valueOf(endTime - startTime));
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		CountDownLatch countDownLatch = new CountDownLatch(3);
		long start = System.currentTimeMillis();
		System.out.println("------主線程開始------");
		myThread t3 = new myThread("線程3", 3,countDownLatch);
		t3.start();
		myThread t1 = new myThread("線程1", 2,countDownLatch);
		t1.start();
		myThread t2 = new myThread("線程2", 5,countDownLatch);
		t2.start();
		countDownLatch.await();
		long end = System.currentTimeMillis();
		System.out.println("主線程執行完畢,耗時:" + String.valueOf(end - start));
	}
}

這個實現了類似上一篇文章的join效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章