Hi_Amos
坚持每天都在进步!!

线程同步工具类,CyclicBarrier日常开发较少涉及,这里只举一个例子,以做备注.N个人一块出去玩,相约去两个地方,CyclicBarrier的主要作用是等待所有人都汇合了,才往下一站出发.

1.效果如下:

 

2.实现代码:

package com.amos.concurrent;

import java.util.Random;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/** 
* @ClassName: CyclicBarrierTest 
* @Description: 线程同步工具类,CyclicBarrier的主要作用是等待所有人都汇合了,才往下一站出发,日常应用中较少涉及
* @author: amosli
* @email:hi_amos@outlook.com
* @date Apr 25, 2014 1:35:34 AM  
*/
public class CyclicBarrierTest {
    public static void main(String[] args) {
        final CyclicBarrier cyclicBarrier = new CyclicBarrier(3);
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
        for(int i=0;i<3;i++){
            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    System.out.println("线程"+Thread.currentThread().getName()+"即将到达集合点1"+",当前已有"+(cyclicBarrier.getNumberWaiting()==2?(cyclicBarrier.getNumberWaiting()+1)+"人,人数已经集合完毕,即将向下一站进发":(cyclicBarrier.getNumberWaiting()+1)+"人"));
                    try {
                        cyclicBarrier.await();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    } 
                    
                    try {
                        Thread.sleep(new Random().nextInt(1000));
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                    System.out.println("线程"+Thread.currentThread().getName()+"即将到达集合点2"+",当前已有"+(cyclicBarrier.getNumberWaiting()==2?(cyclicBarrier.getNumberWaiting()+1)+"人,人数已经集合完毕,即将向下一站进发":(cyclicBarrier.getNumberWaiting()+1)+"人"));
                    try {
                        cyclicBarrier.await();
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    } 
                    
                }
            };
            newCachedThreadPool.execute(runnable);
        }
        newCachedThreadPool.shutdown();
    }
}

 

3.用法:

1),如何创建?

CyclicBarrier cyclicBarrier = new CyclicBarrier((int parties);
CyclicBarrier cyclicBarrier =new CyclicBarrier(int parties, Runnable barrierAction)

2).如何控制线程到一个集结点?

cyclicBarrier.await();

调用await()方法即可.

同时可以设置最长待时间,只需要调用await(long timeout, TimeUnit unit)方法即可.

3)如何打破障碍?

breakBarrier(); 

调用breakBarrier() 方法将可以打破当前的障碍.

如果看其内部实现方法不难发现关于Lock锁的应用.

 

 

posted on 2014-04-25 01:49  Hi_Amos  阅读(353)  评论(0编辑  收藏  举报