zoukankan      html  css  js  c++  java
  • 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();
    		}
    	}
    
    }
    

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

  • 相关阅读:
    java基础篇6之代理
    JavaWeb 过滤器应用之页面静态化
    JavaWeb 之过滤器
    JavaWeb 之监听器
    分页
    Linux 入门
    多条件组合查询
    Service 事务(JdbcUtils 升级)
    BaseServlet 介绍
    dbUtils 工具类介绍
  • 原文地址:https://www.cnblogs.com/huanchupkblog/p/8037715.html
Copyright © 2011-2022 走看看