zoukankan      html  css  js  c++  java
  • javaCountDownLatch闭锁

    package com.java.concurrent;
    
    import java.util.concurrent.CountDownLatch;
    /**
     * CountDownLatch: 闭锁,在完成某些运算的时候,只有其它所有线程的运算全部完成后,当前运算才会执行
     * @author fliay
     *
     */
    public class TestCountDownLatch {
    
    	public static void main(String[] args) {
    		final CountDownLatch latch = new CountDownLatch(10);
    		LactchDemo Ld = new LactchDemo(latch);
    		long start = System.currentTimeMillis();
    		for (int i = 0; i < 5; i++) {
    			new Thread(Ld).start();
    			new Thread(Ld).start();
    		}
    		
    		try {
    			latch.await();//执行等待
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		long end = System.currentTimeMillis();
    		System.out.println("消耗时间为:" + (end - start));
    		
    	}
    
    }
    
    class LactchDemo implements Runnable {
    
    	private CountDownLatch latch;
    
    	public LactchDemo(CountDownLatch latch) {
    		this.latch = latch;
    	}
    
    	public void run() {
    		synchronized (this) {
    			try {
    				for (int i = 0; i < 10; i++) {
    					if (i % 2 == 0) {
    						System.out.println(i);
    					}
    				}
    			} finally {
    				// 启动闭锁
    				latch.countDown();
    			}
    		}
    
    	}
    
    }
    

      

  • 相关阅读:
    143. Reorder List
    圆圈中最后剩下的数
    求1+2+3+...+n
    不用加减乘除做加法
    构建乘积数组
    199. Binary Tree Right Side View
    把字符串转换成整数
    java stream
    物流运费的维护架构
    9、定义类与方法
  • 原文地址:https://www.cnblogs.com/fliay/p/7651039.html
Copyright © 2011-2022 走看看