1. 程式人生 > >Java-CyclicBarrier的簡單例子

Java-CyclicBarrier的簡單例子

內容:一個主任務等待兩個子任務,通過CyclicBarrier的await()實現,此Runnable任務在CyclicBarrier的數目達到後,所有其它執行緒被喚醒前被執行。

public class CyclicBarrierTest {
	
	class MainTask implements Runnable {
		@Override
		public void run() {
			System.out.println(">>>>主任務開始執行!<<<<");
		}
	}
	
	class SubTask implements Runnable {
		private String name;
		private CyclicBarrier cyclicBarrier;
		
		SubTask(String name, CyclicBarrier cyclicBarrier) {
			this.name = name;
			this.cyclicBarrier = cyclicBarrier;
		}
		
		@Override
		public void run() {
			System.out.println("[子任務" + name + "]開始執行了!");
			for (int i = 0; i < 999999; i++) ;
			System.out.println("[子任務" + name + "]執行完成了,並通知障礙器已經完成了");
			
			try {
				cyclicBarrier.await();
			} catch (InterruptedException  e) {
				e.printStackTrace();
			} catch (BrokenBarrierException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		CyclicBarrierTest test = new CyclicBarrierTest();
		CyclicBarrier cyclicBarrier = new CyclicBarrier(2, test.new MainTask());
		SubTask A = test.new SubTask("A", cyclicBarrier);
		SubTask B = test.new SubTask("B", cyclicBarrier);
		ExecutorService executor = Executors.newCachedThreadPool();
		executor.execute(A);
		executor.execute(B);
	}
}