• 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();
    		}
    
    	}
    	
    }
    
  • 相关阅读:
    165. Compare Version Numbers
    163. Missing Ranges
    162. Find Peak Element
    161. One Edit Distance
    156. Binary Tree Upside Down
    工欲善其事-Eclipse设置
    2016年1月15日面试某互联网公司总结(一)
    以前用SQL实现的机构职能树,再看看
    Sublime3学习笔记
    Android之EACCES (Permission denied)与Permission denied异常探密
  • 原文地址:https://www.cnblogs.com/tandi19960505/p/9707827.html
Copyright © 2020-2023  润新知