zoukankan      html  css  js  c++  java
  • 多线程辅助类之CountDownLatch(三)

    CountDownLatch信号灯是一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。它可以实现多线程的同步互斥功能,和wait和notify方法实现功能类似,具体的实现代码如下:

    package face.thread.CountDownLatch;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.concurrent.CountDownLatch;
    
    public class CountDownLatchDemo3 {
    	
    	public static void main(String[] args) {
    		
    		int capaCity = 3;
    		final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    		final CountDownLatch start = new CountDownLatch(1);
    		final CountDownLatch startAnswer = new CountDownLatch(capaCity);
    		
    		final CountDownLatch end = new CountDownLatch(1);
    		final CountDownLatch endAnswer = new CountDownLatch(capaCity);
    		
    		for(int i=0; i<capaCity; i++){
    			new Thread(new Runnable() {
    				public void run() {
    					System.out.println(Thread.currentThread().getName() +"运动员准备就绪," + sdf.format(new Date()));
    					try {
    						startAnswer.countDown();
    						start.await();
    						Thread.sleep(1000);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}finally{
    						System.out.println(Thread.currentThread().getName() +"运动员结束比赛," + sdf.format(new Date()));
    						endAnswer.countDown();
    					}
    				}
    			}).start();
    		}
    		
    		try {
    			startAnswer.await();
    			System.out.println("比赛开始:" + sdf.format(new Date()));
    			start.countDown();
    			
    			endAnswer.await();
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			System.out.println("比赛结束:" + sdf.format(new Date()));
    		}
    	}
    }
    具体的说明参照Jdk Api,参照此例子加以理解
  • 相关阅读:
    (73)C# 扩展方法
    网络
    (十九)守护进程
    (十二)函数返回局部变量
    (十八)WireShark 过滤语法
    (十七)linux网络命令 vconfig ifconfig
    (十六)getsockname()
    (十五)ioctl、ifreq、ifconf
    (十四)UDP协议的两个主要方法sendto和recvfrom详解
    (十三)Packet socket 和 sockaddr_ll
  • 原文地址:https://www.cnblogs.com/chen1-kerr/p/6900031.html
Copyright © 2011-2022 走看看