首页 > 代码库 > 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的区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。