`
lg_asus
  • 浏览: 184945 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

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();
			}
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics