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();
		}

	}
	
}
原文地址:https://www.cnblogs.com/tandi19960505/p/9707827.html