好记性不如铅笔头

java, think_in_java, 编程

《Java编程思想》读书笔记:CountDownLatch

最近在整理 Java 的多线程相关的技术,这里备份下关于【 CountDownLatch 】代码。

github:

【 https://github.com/cstriker1407/think_in_java 】

CountDownLatch主要用来完成一个计数器锁的业务,即计数完成前线程会等待。这里备份下代码:

public class CountDownLatchTest
{
	public static void test()
	{
		CountDownLatch startSignal = new CountDownLatch(1);
		CountDownLatch doneSignal = new CountDownLatch(3);

		for (int i = 0; i < 3; ++i)
		{
			new Thread(new Worker(startSignal, doneSignal)).start();
		}

		try
		{
			Thread.sleep(1000);
		}
		catch (InterruptedException e1)
		{
			e1.printStackTrace();
		}
		System.out.println("the runnables are inited");
		System.out.println("the runnables are free to start");
		startSignal.countDown();
		
		try
		{
			doneSignal.await();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		} 
	}
}

class Worker implements Runnable
{
	private static int count = 0;
	private int idx = 0;
	private final CountDownLatch startSignal;
	private final CountDownLatch doneSignal;

	Worker(CountDownLatch startSignal, CountDownLatch doneSignal)
	{
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
		idx = count++;
	}

	public void run()
	{
		try
		{
			System.out.println("the runnable is begin to init:" + idx);
			startSignal.await();
			System.out.println("the runnable is begin to start:" + idx);
			Thread.sleep(2000);

			doneSignal.countDown();
			System.out.println("the runnable is finish:" + idx);
		}
		catch (InterruptedException ex)
		{
		} // return;
	}
}

 日志显示:

the runnable is begin to init:0
the runnable is begin to init:2
the runnable is begin to init:1
the runnables are inited
the runnables are free to start
the runnable is begin to start:2
the runnable is begin to start:1
the runnable is begin to start:0
the runnable is finish:1
the runnable is finish:0
the runnable is finish:2

 

发表评论

15 − 12 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据