【CountDownLatch】实现多个线程同时启动

要点:

1、 CountDownLatch的计数是1.

2、await发生在多个子线程,主线程负责countDown,相当于管理多个线程的同步时机。

package multithread;

import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.CountDownLatch;

public class CountDownLatchSyncStart {
	@SuppressWarnings("unchecked")
	public static void main(String[] args) throws InterruptedException {
		
		CountDownLatchSyncStart test = new CountDownLatchSyncStart();

		CountDownLatch latch = new CountDownLatch(1);
		
		Thread t1 = new Thread(test.new MapOper(latch));
		Thread t2 = new Thread(test.new MapOper(latch));
		
		t1.setName("Thread1");
		t2.setName("Thread2");
		t1.start();
		t2.start();
		
		System.out.println("thread already start, sleep for a while...");
		
		Thread.sleep(1000);
		latch.countDown();
		
	}
	
	public class MapOper implements Runnable {
		
		CountDownLatch latch ;

		public MapOper(CountDownLatch latch) {
			this.latch = latch;
		}

		public void run() {
			try {
				latch.await();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+" Sync Started!");
		}
	}
}


你可能感兴趣的:(【CountDownLatch】实现多个线程同时启动)