CountDownLatch 闭锁

一、CountDownLatch :闭锁,在完成某些运算是,只有其他所有线程的运算全部完成,当前运算才继续执行

public void await() throws InterruptedException { };   //调用await()方法的线程会被挂起,它会等待直到count值为0才继续执行
public boolean await(long timeout, TimeUnit unit) throws InterruptedException { };  //和await()类似,只不过等待一定的时间后count值还没变为0的话就会继续执行
public void countDown() { };  //将count值减1

二、

    public class TestCountDownLatch {
              public static void main(String[] args) {
	            final CountDownLatch latch = new CountDownLatch(5); //
	            LatchDemo ld = new LatchDemo(latch);

	            long start = System.currentTimeMillis();

	            for (int i = 0; i < 5; i++) {
		            new Thread(ld).start();
	            }

	            try {
		          latch.await(); // 等待所有线程执行完成
	            } catch (InterruptedException e) {
	            }

	            long end = System.currentTimeMillis();

	            System.out.println("耗费时间为:" + (end - start));
         }

        }

              class LatchDemo implements Runnable {

                  private CountDownLatch latch;

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

                  @Override
                  public void run() {

	                  try {
		                  for (int i = 0; i < 50000; i++) {
			               if (i % 2 == 0) {
				       System.out.println(i);
			            }
		            }
	                  } finally {
		                  latch.countDown(); // 5个线程,每个线程执行完后,latch的数量都减一,所以初始化时latch的数量 = 线程数量
	                  }                  

                  }

              }
posted @ 2020-11-29 02:56  jock_javaEE  阅读(75)  评论(0编辑  收藏  举报