CountDownLatch 导致主线程一直等待的问题

CountDownLatch 的作用: 能够使一个线程等待其他线程完成各自的工作后再执行. 

这里实现的是主线程等待子线程跑完才继续执行.

下面是存在问题的代码片段:

@Test
	public void test2() throws InterruptedException {
		int threadNum = 5;
		AtomicInteger atomic = new AtomicInteger();

		Executor executor = Executors.newFixedThreadPool(threadNum);
		CountDownLatch latch = new CountDownLatch(200);
		for(int i=0;i<20;i++) {
		executor.execute(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread thread = Thread.currentThread();
					System.out.println(String.format("thread  id  %s , thread name : %s . start", thread.getId(),
							thread.getName()));
				} catch (Exception e) {
					// TODO: handle exception
				} finally {
					atomic.incrementAndGet();
					latch.countDown();
				}
			}

		});
		
	}
	latch.await();
	System.out.println(String.format("thread is running off ,latch of count is %s , atomic = %s ",latch.getCount(),atomic.get()));
	}

代码的逻辑是: 线程池的容量为5个, 实际线程执行数为20次 , 测试在多线程环境下 AtomicInteger  是否线程安全. 在这里面利用了CountDownLatch  线程等待api .

CountDownLatch  初始化的数量为200 ,  导致主线程一直被挂起. 

原因: 当线程执行次数到20次时, 子线程执行已经执行完了, 但CountDownLatch.getCount() 此时还剩下180.

也就是说countDown 执行的次数一定要保证与CountDownLatch初始化的值一致. 才不会导致线程一直挂住.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值