• 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();
    		}
    	}
    
    }
    

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

  • 相关阅读:
    2021 发工资咯:)
    HDU-2021
    HDU-2020
    HDU-2019
    HDU-2018
    HDU-2017
    HDU-2016
    HDU-2015
    HDU-2014
    HDU-2013
  • 原文地址:https://www.cnblogs.com/huanchupkblog/p/8037715.html
Copyright © 2020-2023  润新知