简单介绍CountDownLatch(闭锁)的使用

CountDownLatch(闭锁)一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个线程或多个线程一直等待(只有等到其他线程全部执行完成,当前运算才执行 )

使用是个线程,打印出10000以内的偶数,并打印花费的时间
1,不适用CountDownLatch情况下

package com.test1;
/**
 * 
 * @author 冷浪进
 * @date 2020年4月29日 上午11:57:37
 */
public class TestCountDownLatch {
	public static void main(String[] args) {
		TestThread tt = new TestThread();
		long start = System.currentTimeMillis();
		for (int i = 0; i < 10; i++) {
			new Thread(tt).start();
		}
		long end = System.currentTimeMillis();
		System.out.println("执行时间:"+(end-start));
	}
}

class TestThread implements Runnable {

	@Override
	public void run() {
		synchronized (this) {
			for (int i = 0; i < 10000; i++) {
				if(i%2==0) {
					System.out.println(i);
				}
			}
		}
		
	} 
	
}

2,运行结果:并没有打印出消耗时间,因为线程执行没有固定的顺序,所以消耗时间可能提前就打印出来了!
在这里插入图片描述
2,使用CountDownLatch(闭锁),使得主线程最后执行完成打印出消耗时间

package com.test1;

import java.util.concurrent.CountDownLatch;

/**
 * 
 * @author 冷浪进
 * @date 2020年4月29日 上午11:57:37
 */
public class TestCountDownLatch {
	public static void main(String[] args) {
		CountDownLatch latch = new CountDownLatch(10);
		TestThread tt = new TestThread(latch);
		long start = System.currentTimeMillis();
		for (int i = 0; i < 10; i++) {
			new Thread(tt).start();
		}
		try {
			latch.await();//保证下面的最后执行
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		long end = System.currentTimeMillis();
		System.out.println("执行时间:"+(end-start));
	}
}

class TestThread implements Runnable {
	private CountDownLatch latch;
	
	public TestThread(CountDownLatch latch) {
		this.latch = latch;
	}
	@Override
	public void run() {
		synchronized (this) {
			try {
				for (int i = 0; i < 10000; i++) {
					if(i%2==0) {
						System.out.println(i);
					}
				}
			} finally {
				latch.countDown();
			}
			
		}
		
	} 
	
}

2,运行结果:打印出了执行时间
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值