java线程之CountDownLatch

本文通过一个具体的Java示例,详细介绍了CountDownLatch的使用方法及原理。该示例创建了一个包含10个线程的任务,利用CountDownLatch确保所有子线程完成后再继续执行主线程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CountDownLatch就是个倒计的计数器,用法如下:

package com.concurrent;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import junit.framework.TestCase;

public class TestCountDownLatch extends TestCase {
	private final int COUNT = 10;

	public void testCountDownLatch() {
		final CountDownLatch cdl = new CountDownLatch(COUNT);
		final Random random = new Random();
		ExecutorService executorService = Executors.newFixedThreadPool(COUNT);
		for (int i = 0; i < COUNT; i++) {
			final int index = i + 1;
			Runnable r = new Runnable() {
				@Override
				public void run() {
					try {
						System.out.println("begin to work " + index);
						Thread.sleep(random.nextInt(10) * 1000);
						System.out.println("end " + index);
					} catch (InterruptedException e) {
						e.printStackTrace();
					} finally {
						cdl.countDown();
					}
				}
			};
			executorService.submit(r);
		}
		try {
			cdl.await();
			System.out.println("testCountDownLatch");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		executorService.shutdown();
	}
}


总共有11个线程,主线程里生成了10个线程,主线程等10个线程全部运行结束后,再输出testCountDownLatch

运行结果如下:

begin to work 1
begin to work 3
begin to work 2
begin to work 5
begin to work 6
begin to work 4
end 4
begin to work 7
begin to work 8
begin to work 9
begin to work 10
end 9
end 3
end 1
end 7
end 2
end 10
end 8
end 5
end 6
testCountDownLatch


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值