首页 > 代码库 > CyclicBarrier与CountDownLatch的区别

CyclicBarrier与CountDownLatch的区别

import java.util.concurrent.CountDownLatch;
/**
 * 作用于单个线程或几个线程,,在其他线程执行完之前,一直等待(await)知道countDown为零
 * @author Administrator
 *
 */
public class CountDownlatchTest {  
    public static void main(String[] args) throws InterruptedException {  
        CountDownLatch countDownLatch = new CountDownLatch(5);  
        for(int i=0;i<5;i++){  
            new Thread(new readNum(i,countDownLatch)).start();  
        }  
        countDownLatch.await();  
        System.out.println("线程执行结束。。。。");  
    }  
  
    static class readNum  implements Runnable{  
        private int id;  
        private CountDownLatch latch;  
        public readNum(int id,CountDownLatch latch){  
            this.id = id;  
            this.latch = latch;  
        }  
        @Override  
        public void run() {  
            synchronized (this){  
                System.out.println("id:"+id);
                latch.countDown();
                System.out.println("线程组任务"+id+"结束,其他任务继续");
            }  
        }  
    }  
}  
/**
 * 作用于多个线程
 * 可以通过CyclicBarrier实现没有先后顺序的同时执行任意的线程(假设cpu也是任意个)
 * 多个线程一直阻塞,直到await数量达到CyclicBarrier的参数时,唤醒阻塞的线程
 * 可重用
 * @author Administrator
 *
 */
public class CyclicBarrierTest {  
    public static void main(String[] args) throws InterruptedException {  
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5, new Runnable() {  
            @Override  
            public void run() {  
                System.out.println("线程组执行结束");  
            }  
        });  
        for (int i = 0; i < 5; i++) {  
            new Thread(new readNum(i,cyclicBarrier)).start();  
        }  
        //CyclicBarrier 可以重复利用,  
        // 这个是CountDownLatch做不到的  
//        for (int i = 11; i < 16; i++) {  
//            new Thread(new readNum(i,cyclicBarrier)).start();  
//        }  
    }  
    static class readNum  implements Runnable{  
        private int id;  
        private CyclicBarrier cyc;  
        public readNum(int id,CyclicBarrier cyc){  
            this.id = id;  
            this.cyc = cyc;  
        }  
        @Override  
        public void run() {  
            synchronized (this){  
                System.out.println("id:"+id);  
                try {  
                    cyc.await();  
                    System.out.println("线程组任务" + id + "结束,其他任务继续");  
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  
}  

 

CyclicBarrier与CountDownLatch的区别