CountDownLatch的用法

本文介绍了一个线程同步辅助类CountDownLatch的基本用法及其在多线程环境中的应用案例。通过两个跑步者完成跑步任务的示例,展示了如何利用CountDownLatch确保所有线程完成指定操作后继续执行后续流程。

       CountDownLatch,是线程同步辅助类,在一组执行线程中有未完成的线程时,可以让已完成的线程一直等待其他线程完成。设计理念有点类似于团队爬山,前队等后队,人到齐后才算爬山任务完成。

       下面的例子模仿有两个人abtest和unittest,两个人跑步,只有两个人都跑完后,才是真正的跑步结束,才打印跑步结束语句,所以打印跑步结束语句的动物要在两个人(线程)跑完步动作之后。

/**
 * Description
 * 
 * @author usr1999 2015-1-13
 */
public class CountDownLatchDemo2 {

	/**
	 * 
	 */
	public static void main(String[] args) {
		CountDownLatch latch = new CountDownLatch(2);

		Runner run1 = new Runner("abtest", 3000, latch);
		Runner run2 = new Runner("unittest", 5000, latch);

		ExecutorService exec = Executors.newFixedThreadPool(2);
		exec.submit(run1);
		exec.submit(run2);

		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		System.out.println("abtest and unittest completed running");
		exec.shutdown();
	}
}

class Runner implements Runnable {
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	String name;
	int time;
	CountDownLatch latch;

	public Runner(String name, int time, CountDownLatch latch) {
		this.name = name;
		this.time = time;
		this.latch = latch;
	}

	@Override
	public void run() {
		System.out.println(name + " is ready to run at "
				+ sdf.format(new Date()));
		doRun();
		System.out.println(name + " has runed at " + sdf.format(new Date()));
		latch.countDown(); // 计数递减
	}

	private void doRun() {
		try {
			TimeUnit.MILLISECONDS.sleep(time);
			// Thread.sleep(time);
		} catch (InterruptedException e) {
			System.out.println(e.getStackTrace());
		}
	}
}

      

 CountDownLatch主要有三个方法:

       CountDownLatch(int count),构造函数,参数为计数的数目。
       countDown(), 计数递减,如果计数减到0,则释放所有等待状态的线程。
       await(), 线程阻塞方法,使当前线程在计数变为0之前一直等待,直到count值为0才继续执行。

 

CountDownLatch是Java中提供的一个同步工具类,它可以用来控制一个或多个线程等待多个线程的操作完成。 CountDownLatch用法如下: 1. 创建一个CountDownLatch对象,指定需要等待的线程数。 ``` CountDownLatch latch = new CountDownLatch(5); ``` 2. 每个需要等待的线程执行完后调用CountDownLatch的countDown方法减少计数器。 ``` latch.countDown(); ``` 3. 等待所有线程执行完毕后,调用CountDownLatch的await方法进行等待。 ``` latch.await(); ``` 4. 在所有线程执行完毕后,主线程或其他线程可以继续执行自己的操作。 示例代码: ``` import java.util.concurrent.CountDownLatch; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(5); for (int i = 0; i < 5; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + " is working..."); try { // 模拟线程执行时间 Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " done"); latch.countDown(); }).start(); } System.out.println("Waiting for all threads to finish..."); latch.await(); System.out.println("All threads have finished, continue to execute the main thread."); } } ``` 运行结果: ``` Waiting for all threads to finish... Thread-0 is working... Thread-2 is working... Thread-1 is working... Thread-3 is working... Thread-4 is working... Thread-1 done Thread-3 done Thread-0 done Thread-2 done Thread-4 done All threads have finished, continue to execute the main thread. ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值