CyclicBarrier example

package com.jibx_maven;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class BarrierTest {

	public static void main(String[] args) {
		 CyclicBarrier barrier = new CyclicBarrier(4, new Runnable() {
			@Override
			public void run() {
				
				System.out.println("ALL counting finished , starting summarizing ");
			}
		});
		 
		 new Thread(new BarrierTask("beijing", barrier)).start();
		 new Thread(new BarrierTask("shanghai", barrier)).start();
		 new Thread(new BarrierTask("guangzhou", barrier)).start();
		 new Thread(new BarrierTask("shenzhen", barrier)).start();
	}
}
class BarrierTask implements Runnable{

	private String code;
	private CyclicBarrier barrier ;
	@Override
	public void run() {
		System.out.println(code+ " starting counting...........");
		Random random = new Random();
		try {
			Thread.sleep(random.nextInt(20)*1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(code+ " finish counting...........");
		try {
			barrier.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BrokenBarrierException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public BarrierTask(String code, CyclicBarrier barrier) {
		super();
		this.code = code;
		this.barrier = barrier;
	}
	
	
}

你可能感兴趣的:(thread)