Java - CyclicBarrier

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/PeersLee/article/details/79949780
package Chapter02;

import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

/*
 * CyclicBarrier:
 * 1. 同步屏障
 * 2. 计数器为0
 * 3. await时,计数器加1
 * 4. 具有屏障重置性
 */
public class _02_Run {
	
	static void prepareClimb(CyclicBarrier cBarrier, CountDownLatch cdLatch,
			String id) {
		try {
			System.out.println("同学 "+ id+ " 接到爬山计划通知.");
			cBarrier.await();
			
			System.out.println("同学 "+ id+ " 正在赶往集合地.");
			cBarrier.await(); //屏障重置性
			
			System.out.println("同学 "+ id+ " 到达目的地.");
			cBarrier.await();
			
			cdLatch.countDown();
		} catch (Exception e) { }
	}
	
	public static void main(String[] args) {
		CountDownLatch cdLatch = new CountDownLatch(5);
		CyclicBarrier cBarrier = new CyclicBarrier(5, new Runnable() {
			@Override
			public void run() {
				System.out.println("---------------------");
			}
		});
		
		Arrays.asList("a", "b", "c", "d", "e").forEach(id -> {
			// lambda表达式 -> 函数式接口,来创建实例
			new Thread(() -> {
				prepareClimb(cBarrier, cdLatch, id);
			}).start();
		});
		
		try {
			cdLatch.await();
		} catch (InterruptedException e) { }
		System.out.println("所有同学都已到达,开始进行爬山计划.");
	}
}

同学 a 接到爬山计划通知.
同学 e 接到爬山计划通知.
同学 c 接到爬山计划通知.
同学 b 接到爬山计划通知.
同学 d 接到爬山计划通知.
---------------------
同学 d 正在赶往集合地.
同学 a 正在赶往集合地.
同学 b 正在赶往集合地.
同学 c 正在赶往集合地.
同学 e 正在赶往集合地.
---------------------
同学 e 到达目的地.
同学 d 到达目的地.
同学 a 到达目的地.
同学 b 到达目的地.
同学 c 到达目的地.
---------------------
所有同学都已到达,开始进行爬山计划.

猜你喜欢

转载自blog.csdn.net/PeersLee/article/details/79949780
今日推荐