CountDownLatch and usage CyclicBarrier

CountDownLatch

Role: is a group of threads waiting for other threads to complete the work after the execution, enhanced join

to await wait, countDown counter by a responsible

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

Let a group of threads reaches a certain barrier, blocked, until the group reaches the last thread barrier, barrier open, all the blocked thread will continue to run

CyclicBarrier (int parties) CyclicBarrier (int parties, Runnable barrierAction), barrier open, barrierAction defined task execution

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 and CyclicBarrier Discrimination

  1. countdownlatch release is controlled by a third party, CyclicBarrier release itself controlled by a set of threads
  2. countdownlatch release conditions "= number of threads, CyclicBarrier dispatch conditions = number of threads

Guess you like

Origin juejin.im/post/5d7b331af265da03d155802f