zoukankan      html  css  js  c++  java
  • CountDownLatch、CyclicBarrier

    CountDownLatch

    public class T1 {
    
    	volatile List<Integer> list = new ArrayList<>();
    	
    	public void add(int num) {
    		list.add(num);
    	}
    	
    	public int size() {
    		return list.size();
    	}
    	
    	/**
    	 * 	需求:
    	 * 		容器元素不足5的时候让线程1等待
    	 * 		容器元素足5时唤醒线程1
    	 */
    	public static void main(String[] args) {
    		T1 t = new T1();
    		
    		// 构造器:CountDownLatch(int count)
    		CountDownLatch countDownLatch = new CountDownLatch(1);
    		
    		// 线程1
    		new Thread(()->{
    			System.out.println("线程1启动");
    			if(t.size() != 5) {
    				try {
    					countDownLatch.await();
    				} catch (InterruptedException e) {
    					e.printStackTrace();
    				}
    			}
    			System.out.println("线程1结束");
    		}).start();
    		
    		// 线程2
    		new Thread(()->{
    			System.out.println("线程2启动");
    			for(int i=1; i<=5; i++) {
    				t.add(i);
    				System.out.println(t.size());
    			}
    			System.out.println("线程2结束");
    			
    			/**
    			 * 	将CountDownLatch中的count减一,当count为0则唤醒被
    			 * 	CountDownLatch await的线程
    			 */
    			countDownLatch.countDown(); 
    		}).start();
    	}
    	
    }
    
    

    CyclicBarrier

    public class T2 {
    
    	volatile List<Integer> list = new ArrayList<>();
    	
    	public void add(int num) {
    		list.add(num);
    	}
    	
    	public int size() {
    		return list.size();
    	}
    	
    	/**
    	 * 	需求:
    	 */
    	public static void main(String[] args) {
    		T1 t = new T1();
    		
    		// 构造器:CyclicBarrier(int parties)
    		// 当await的线程数等于parties的时候,所有的await线程就会被唤醒
    		CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
    		for(int i=0; i<5; i++) {
    			new Thread(()->{
    				System.out.println("线程启动");
    				try {
    					cyclicBarrier.await();
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    				System.out.println("线程结束");
    			}).start();
    		}
    
    	}
    	
    }
    
  • 相关阅读:
    js rsa sign使用笔记(加密,解密,签名,验签)
    金额的计算
    常用js方法集合
    sourceTree 的使用
    node-- express()模块
    详细讲解vue.js里的父子组件通信(props和$emit)
    Vue -- vue-cli webpack打包开启Gzip 报错
    es6函数的rest参数和拓展运算符(...)的解析
    js中判断对象数据类型的方法
    vue学习之vue基本功能初探
  • 原文地址:https://www.cnblogs.com/tandi19960505/p/9707827.html
Copyright © 2011-2022 走看看