转载

CountDownLatch 和 CyclicBarrier 的用法

作用:是一组线程等待其他的线程完成工作以后在执行,加强版join

await 用来等待,countDown 负责计数器的减一

public class UseCountDownLatch {
	
	static CountDownLatch latch = new CountDownLatch(6);

    /**
     * 初始化线程(只有一步,有4个)
     */
    private static class InitThread implements Runnable{

        @Override
        public void run() {
            System.out.println("Thread_" + Thread.currentThread().getId() + " ready init work......");
            //初始化线程完成工作了,countDown方法只扣减一次;
        	latch.countDown();
            for(int i =0;i<2;i++) {
            	System.out.println("Thread_"+Thread.currentThread().getId() +" ........continue do its work");
            }
        }
    }
    
    //业务线程
    private static class BusiThread implements Runnable{

        @Override
        public void run() {
        	try {
				latch.await();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
            for(int i =0;i<3;i++) {
            	System.out.println("BusiThread_"+Thread.currentThread().getId()
            			+" do business-----");
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new Thread(new BusiThread()).start();
        for(int i=0;i<=3;i++){
            Thread thread = new Thread(new InitThread());
            thread.start();
        }

        latch.await();
        System.out.println("Main done its work........");
    }
}

复制代码

CyclicBarrier

让一组线程达到某个屏障,被阻塞,一直到组内最后一个线程达到屏障时,屏障开放,所有被阻塞的线程会继续运行

CyclicBarrier(int parties) CyclicBarrier(int parties, Runnable barrierAction),屏障开放,barrierAction 定义的任务会执行

public class UseCyclicBarrier {
	
	private static CyclicBarrier barrier = new CyclicBarrier(5,new CollectThread());

    /**
     * 存放子线程工作结果的容器
     */
    private static ConcurrentHashMap<String,Long> resultMap = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        for(int i=0;i<=4;i++){
            Thread thread = new Thread(new SubThread());
            thread.start();
        }

    }

    /**
     * 负责屏障开放以后的工作
     */
    private static class CollectThread implements Runnable{

        @Override
        public void run() {
            StringBuilder result = new StringBuilder();
            for(Map.Entry<String,Long> workResult:resultMap.entrySet()){
            	result.append("[").append(workResult.getValue()).append("]");
            }
            System.out.println(" the result = "+ result);
            System.out.println("do other business........");
        }
    }

    /**
     * 工作线程
     */
    private static class SubThread implements Runnable{

        @Override
        public void run() {
        	long id = Thread.currentThread().getId();
            resultMap.put(Thread.currentThread().getId() + "", id);
            //随机决定工作线程的是否睡眠
            Random r = new Random();
            try {
                if(r.nextBoolean()) {
                	Thread.sleep(2000+id);
                	System.out.println("Thread_"+id+" ....do something ");
                }
                System.out.println(id+"....is await");
                barrier.await();
            	Thread.sleep(1000+id);
                System.out.println("Thread_"+id+" ....do its business ");
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}

复制代码

CountDownLatch和CyclicBarrier辨析

  1. countdownlatch放行由第三者控制,CyclicBarrier放行由一组线程本身控制
  2. countdownlatch放行条件》=线程数,CyclicBarrier放行条件=线程数
原文  https://juejin.im/post/5d7b331af265da03d155802f
正文到此结束
Loading...