java CountDownLatch 模拟多并发线程简单例子

CountDownLatch作用 

CountDownLatch,是一个倒计数的锁存器,当计数减至0时触发特定的事件。


构造方法参数指定了计数的次数

countDown方法,当前线程调用此方法,则计数减一

awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0



测试线程类

import java.util.concurrent.CountDownLatch;

public class MyTestThread implements Runnable {
	private final CountDownLatch startSignal;
	
	public MyTestThread(CountDownLatch startSignal) {
			super();
			this.startSignal = startSignal;
		}

	@Override
	public void run() {
		try {
			startSignal.await(); //一直阻塞当前线程,直到计时器的值为0
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		doWork();
		
	}

	private void doWork() {
		// TODO Auto-generated method stub
		System.out.println("do work");
	}

}


 
  

测试主函数类 

public class MyTest {

	public static void main(String[] args) {
		 CountDownLatch   start=new CountDownLatch(1);// 初始化计数器为 一
		 for(int i=0;i<16;i++){//模擬16个线程
			 MyTestThread tt =new MyTestThread(start);
			 Thread t = new Thread(tt);
			 t.start();
		 }
	        start.countDown();//计数器減一  所有线程释放 同时跑
	}
}



你可能感兴趣的:(java)