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();
    		}
    
    	}
    	
    }
    
  • 相关阅读:
    上一张作业day16
    python 函数递归,三元表达式解读,匿名一次性函数,模块略解
    迭代器,生成器与内置函数
    闭合函数和装饰器
    函数的其他关键点*与**,函数的对象可以当做变量去使用,函数的嵌套,名称空间
    python函数,应用与讲解
    文件处理方式
    html-04 html骨架
    html-03 Web标准
    html-02 浏览器内核
  • 原文地址:https://www.cnblogs.com/tandi19960505/p/9707827.html
Copyright © 2011-2022 走看看