首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java中CyclicBarrier跟CountDownLatch的异同

2012-12-21 
java中CyclicBarrier和CountDownLatch的异同CountDownLatch只能使用一次,cyclicBarrier可以重复使用,同时

java中CyclicBarrier和CountDownLatch的异同
CountDownLatch只能使用一次,cyclicBarrier可以重复使用,同时还提供barrierAction。 在功能上,cyclicBarrier可以完全替代countdownlatch, 但是性能上,如果同时工作的线程在几百数量级,则两者性能差不多,但是在千/万数量级的线程时,countdownlatch性能远远高于cyclicbarrier。
下面是测试代码,改变count值,观察输出结果:

public class Test2{CyclicBarrierbarrier;CountDownLatchlatch;intcount;longbeginTime;public static void main(String... args){final Test2 t = new Test2();t.count = 5000;t.beginTime = System.currentTimeMillis();t.barrier = new CyclicBarrier(t.count, new Runnable() {@Overridepublic void run(){System.out.println("cyclic barrier time consumed: " + (System.currentTimeMillis() - t.beginTime));}});t.latch = new CountDownLatch(t.count);// t.test();// tatal: 5177344, free: 3357624, used: 1819720 cyclic barrier time consumed: 766// t.test2();// tatal: 5177344, free: 4454904, used: 722440 countdown latch time consumed: 516// long total = Runtime.getRuntime().totalMemory();// long free = Runtime.getRuntime().freeMemory();// System.out.println("tatal: "+ total + ", free: "+ free +", used: "+ (total-free));}/** * cyclic barrier */private void test(){for (int i = 0; i < count; i++){new TestThread().start();}}/** * countdown latch */private void test2(){for (int i = 0; i < count; i++){new TestThread2().start();}try{latch.await();}catch (InterruptedException e){e.printStackTrace();}System.out.println("countdown latch time consumed: " + (System.currentTimeMillis() - beginTime));}class TestThread extends Thread{@Overridepublic void run(){try{Thread.sleep(100);barrier.await();}catch (InterruptedException e){e.printStackTrace();}catch (BrokenBarrierException e){e.printStackTrace();}}}class TestThread2 extends Thread{@Overridepublic void run(){try{Thread.sleep(100);latch.countDown();}catch (InterruptedException e){e.printStackTrace();}}}}

热点排行