CountDownLatch的使用

CountDownLatch是java.util.concurrent包中的类,它的作用是1个线程等待,多个线程唤醒此等待。

CountDownLatch cdl = new CountDownLatch(2);

通过构造方法声明CountDownLatch对象,2这个参数说明一共3个线程。1个线程执行时需要等待,其它的2个线程都进行唤醒操作之后前面的等待线程才能继续执行。

//在此等待阻塞
cdl.await();
//唤醒CountDownLatch的等待
cdl.countDown();

完整列子:

3个线程同时执行,当前两个线程执行完毕发出唤醒通知后,第三个线程才能执行完成。

public static void main(String[] args) {
		CountDownLatch cdl = new CountDownLatch(2);
		Thread t1 = new Thread(new Runnable() {
			@Override
			public void run() {
				System.err.println("线程 " + Thread.currentThread().getName() + " 开始执行。。。");
				try {
					//实际工作中是进行一些业务处理
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				//唤醒线程
				System.err.println("线程 " + Thread.currentThread().getName() + " 进行唤醒操作。。。");
				cdl.countDown();
			}
		},"t1");
		
		Thread t2 = new Thread(new Runnable() {
			@Override
			public void run() {
				System.err.println("线程 " + Thread.currentThread().getName() + " 开始执行。。。");
				try {
					//实际工作中是进行一些业务处理
					Thread.sleep(5000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				//唤醒线程
				System.err.println("线程 " + Thread.currentThread().getName() + " 进行唤醒操作。。。");
				cdl.countDown();
			}
		},"t2");
		Thread t3 = new Thread(new Runnable() {
			@Override
			public void run() {
				System.err.println("线程 " + Thread.currentThread().getName() + " 开始执行并等待其他线程全部唤醒后执行。。。");
				try {
					cdl.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.err.println("线程 " + Thread.currentThread().getName() + " 被其他线程唤醒,继续执行完毕");
			}
		},"t3");
		
		t1.start();
		t2.start();
		t3.start();
	}

结果及分析:

首先t1、t2、t3这三个线程同时执行,其中t3线程进行等待,t1线程内执行完后进行唤醒操作,然后t2线程进行唤醒操作,两个线程都进行唤醒操作后,t3线程开始执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值