CountDownLatch与CyclicBarrier区别

1 CountDownLatch的用途

CountDownLatch类是一个同步计数器,构造时传入int参数,该参数就是计数器的初始值,每调用一次countDown()方法,计数器减1,计数器大于0时,await()方法会阻塞程序继续运行。CountDownLatch能够使一个线程等待其他线程完成各自的工作后再执行。

2 CyclicBarrier的用途

CyclicBarrier的字面意思是可循环使用的屏障。它要做的事情是让一组线程到达一个屏障时被阻塞,直到最后一个线程到达屏障时,屏障才会开门,所以被屏障拦截的线程才会继续干活。每个线程调用await方法告诉CyclicBarrier我已经到达屏障,然后当前线程被阻塞。

3 CountDownLatch与CyclicBarrier区别

1)       CountDownLatch:一个线程或者多个线程,等待另外N个线程完成某个事情之后才能执行。只有一个等待线程,其他N个线程都可以顺利执行完毕。

2)       CyclicBarrier:N个线程互相等待,任何一个线程完成之前,所有线程都必须等待。在最后一个未await之前,所有N个线程都不算完成,都处于阻塞状态。

4 附录

4.1 CountDownLatch 效果演示

package test;

 

import java.util.concurrent.CountDownLatch;

 

public classCountLatchTest {

    public static void main(String[] args){

        CountDownLatchobjectCountDownLatch = newCountDownLatch(3);

        Threadthread1=newThread(){

            public void run(){

            objectCountDownLatch.countDown();

            System.out.println(1);

            }

        };

        thread1.start();

        Threadthread2=newThread(){

            public void run(){

                objectCountDownLatch.countDown();

                System.out.println(2);

            }

        };

        thread2.start();

        Threadthread3=newThread(){

            public void run(){

            //   objectCountDownLatch.countDown();

                System.out.println(3);

            }

        };

        thread3.start();

        try {

            objectCountDownLatch.await();

        }catch(Exception e) {

            System.out.println("Not");

        }

        System.out.println("final");

    }

}

4.2 CyclicBarrier效果演示

package test;

 

import java.util.concurrent.CyclicBarrier;

 

public classTestThread {

    public static void main(String[] args){

        CyclicBarrierobjectCyclicBarrier=new CyclicBarrier(3);

        Threadthread1=newThread(){

            public void run(){

                try{

                    objectCyclicBarrier.await();

                }catch(Exception e){

                   

                }

                System.out.println(1);

            }

        };

        System.out.println(4);

        thread1.start();

        Threadthread2=newThread(){

            public void run(){

                try{

                    objectCyclicBarrier.await();

                }catch(Exception e){

                   

                }

                System.out.println(2);

            }

        };

        thread2.start();

        Threadthread3=newThread(){

            public void run(){

                try{

                    objectCyclicBarrier.await();

                }catch(Exception e){

                   

                }

                System.out.println(3);

            }

        };

        thread3.start();

    }

    }

 

你可能感兴趣的:(CountDownLatch与CyclicBarrier区别)