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,参照此例子加以理解
  • 相关阅读:
    来自平时工作中的javascript知识的积累---持续补充中
    javascript function
    CSS3 3D变换
    HTTP1.1缓存策略
    jQuery插件开发
    mac下好用的工具收录(慢慢完善)
    mac 彻底卸载vscode
    Git冲突:commit your changes or stash them before you can merge. 解决办法(转载)
    关于vscode使用的一些设置
    (linux服务器)apache开启gzip的配置以及效果对比
  • 原文地址:https://www.cnblogs.com/chen1-kerr/p/6900031.html
Copyright © 2011-2022 走看看