CyclicBarrier

 /**
* CyclicBarrier 线程计数器
*
*/
1
import java.util.concurrent.BrokenBarrierException; 2 import java.util.concurrent.CyclicBarrier; 3 4 public class CyclicBarrierTest { 5 private static final int THREAD_COUNT = 10; 6 7 public static CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT); 8 9 public static void main(String[] args) { 10 for(int i = 0; i<THREAD_COUNT; i++){ 11 new Thread(new WorkThread(barrier)).start(); 12 } 13 } 14 15 } 16 17 class WorkThread implements Runnable{ 18 private CyclicBarrier barrier; 19 20 public WorkThread(CyclicBarrier barrier){ 21 this.barrier = barrier; 22 } 23 24 @Override 25 public void run() { 26 try { 27 System.out.println(Thread.currentThread().getName() + "working before await()"); 28 barrier.await();//线程在此等待,直到所有线程到达。。。才开始往下执行 29 System.out.println(Thread.currentThread().getName() + "working after await()"); 30 } catch (InterruptedException e) { 31 e.printStackTrace(); 32 } catch (BrokenBarrierException e) { 33 e.printStackTrace(); 34 } 35 } 36 }

结果

Thread-0working before await()
Thread-1working before await()
Thread-3working before await()
Thread-2working before await()
Thread-5working before await()
Thread-4working before await()
Thread-7working before await()
Thread-9working before await()
Thread-6working before await()
Thread-8working before await()


Thread-0working after await()
Thread-8working after await()
Thread-1working after await()
Thread-3working after await()
Thread-2working after await()
Thread-5working after await()
Thread-4working after await()
Thread-9working after await()
Thread-6working after await()
Thread-7working after await()

 从上面的结果,可以知道:

 CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT); 当调用barrier.await()方法时,当所有线程到达时,才会开始执行后面的代码。这个类很有用,平时自己做一些测试例子是比较常用的
posted @ 2014-08-26 23:26  坚守一辈子的幸福  阅读(274)  评论(0编辑  收藏  举报