zoukankan      html  css  js  c++  java
  • 多线程学习7--CountDownLatch

    CountDownLatch 倒计时器效果,线程在await处停下,当countDown

    为0时就通行

    下面模拟一生令下,三条线程开始执行,等三条线程都执行完之后,然后在进行下一阶段操作

    package com.condition;
    
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class CountDownLatchTest {
    	public static void main(String[] args) {
    		ExecutorService threadPool = Executors.newCachedThreadPool();
    		final CountDownLatch cdOrder = new CountDownLatch(1);
    		final CountDownLatch cdCountDown = new CountDownLatch(3);
    		for(int i = 0;i < 3;i++){
    			Runnable runnable = new Runnable(){
    				    @Override
    					public void run() {
    				    	System.out.println(Thread.currentThread().getName()
    								+" 准备接受命令 ");
    				    	try {
    							cdOrder.await();
    						} catch (InterruptedException e) {
    							e.printStackTrace();
    						}
    				    	System.out.println(Thread.currentThread().getName()
    								+" 正在执行命令 ");
    				    	try {
    							Thread.sleep((long) (Math.random()*1000));
    						} catch (InterruptedException e) {
    							// TODO Auto-generated catch block
    							e.printStackTrace();
    						}
    				    	System.out.println(Thread.currentThread().getName()
    								+" 正在回应 ");
    				    	cdCountDown.countDown();
    				    }
    			};
    			 threadPool.execute(runnable);
    		}	
    		try {
    			Thread.sleep((long) (Math.random()*1000));
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		synchronized(threadPool){
    			System.out.println(Thread.currentThread().getName()
    					+" 即将发布命令 ");
    			cdOrder.countDown();
    			System.out.println(Thread.currentThread().getName()
    					+" 正在发布命令 ");
    		}
    		try {
    			cdCountDown.await();
    		} catch (InterruptedException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		System.out.println(Thread.currentThread().getName()
    				+" 收到所有结果 ");
    	}
    
    }
    

      

  • 相关阅读:
    WEP编码格式
    OSK VFS read数据流分析
    科学剖析濒死体验 "复生"者讲述"死"前1秒钟
    Android的开发相对于tizen的开发难度
    minix文件系统分析
    贴给小程序(1) 查找第一个0值
    Linux下的QQ
    OSK USB 驱动
    LRU算法之hash+list实现(转)
    插入排序
  • 原文地址:https://www.cnblogs.com/hzmbbbb/p/4280300.html
Copyright © 2011-2022 走看看