• 6. CountDownLatch 闭锁


    package com.gf.demo05;
    
    import java.util.concurrent.CountDownLatch;
    
    /**
     * CountDownLatch : 闭锁,在完成某些操作时,只有其他所有的线程运算全部完成,当前运算才继续向下执行。
     *
     */
    public class TestCountDownLatch {
    
    	public static void main(String[] args) {
    		
    		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) {
    			e.printStackTrace();
    		}
    		
    		long end = System.currentTimeMillis();
    		
    		System.out.println("耗费时间为:" + (end - start));
    		
    
    	}
    
    }
    
    class LatchDemo implements Runnable {
    
    	private CountDownLatch latch;
    
    	public CountDownLatch getLatch() {
    		return latch;
    	}
    
    	public void setLatch(CountDownLatch latch) {
    		this.latch = latch;
    	}
    
    	public LatchDemo(CountDownLatch latch) {
    		this.latch = latch;
    	}
    
    	@Override
    	public void run() {
    		try {
    			
    			for (int i = 0; i < 5000; i++) {
    				if (i % 2 == 0) {
    					System.out.println(i);
    				}
    			}
    		} finally {
    			latch.countDown();
    		}
    	}
    
    }
    

    关注我的公众号,精彩内容不能错过

  • 相关阅读:
    QR code
    复制一个带random指针的链表
    运行时const
    海量处理 bitmap及区段划分
    socket编程随记
    BLS签名
    load balancing
    Bloom Filter (2)
    #include 的花样
    拓扑排序、Dijkstra、Prim/Kruskal、全部最短路径/传递闭包
  • 原文地址:https://www.cnblogs.com/huanchupkblog/p/8037715.html
Copyright © 2020-2023  润新知