java中CyclicBarrier和CountDownLatch的异同

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

public class Test2
{
CyclicBarrier barrier;
CountDownLatch latch;
int count;
long beginTime;

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() {

@Override
public 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
{

@Override
public void run()
{
try
{
Thread.sleep(100);

barrier.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (BrokenBarrierException e)
{
e.printStackTrace();
}
}

}

class TestThread2 extends Thread
{

@Override
public void run()
{
try
{
Thread.sleep(100);

latch.countDown();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值