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()
    				+" 收到所有结果 ");
    	}
    
    }
    

      

  • 相关阅读:
    关于MFC消息的总结
    关于VS中包含库、附加包含库、
    关于MFC中重载函数是否调用基类相对应函数的问题
    关于子窗口处理自身消息而不扩散给父窗口的问题
    进程与线程理解-1
    程序设计思想-2
    线程与进程
    网路编程之socket与 socketserver、黏包
    网络编程之TCP协议与UDP协议
    网络编程基础
  • 原文地址:https://www.cnblogs.com/hzmbbbb/p/4280300.html
Copyright © 2011-2022 走看看