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

      

  • 相关阅读:
    Servlet
    反射
    Python之装饰器
    app——升级测试点
    Python之基本运算符
    HTTP常见的几种认证机制
    Shell文件包含
    Shell输入/输出重定向
    Shell函数
    Shell循环语句
  • 原文地址:https://www.cnblogs.com/hzmbbbb/p/4280300.html
Copyright © 2011-2022 走看看