线程同步之CountDownLatch

如何保证线程安全我们都知道,像synchronized,lock等,线程同步使用什么方法呢,这里给大家介绍一个工具CountDownLatch

CountDownLatch可以理解为一个线程同步门闩,它基于AbstractQueueSynchronizer包实现的,具体实现方式大家可以看下源码,这里只对其功能做一个分享

功能主要针对,当一定线程执行完毕后,才执行后面的代码

我们看下面一个例子

public class CountDownLatchDemo {

	public static void main(String[] args) throws InterruptedException {
		Runnable runnable = new Runnable() {
			Thread thread = Thread.currentThread();
			@Override
			public void run() {
				System.out.println("thread:"+thread.currentThread().getName()+" start");
				try {
					thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("thread:"+thread.currentThread().getName()+" end");
			}
		};
		Thread thread1 = new Thread(runnable);
		Thread thread2 = new Thread(runnable);
		Thread thread3 = new Thread(runnable);
		Thread thread4 = new Thread(runnable);
		
		thread1.start();
		thread2.start();
		thread3.start();
		thread4.start();
		System.out.println("mainThread end:"+Thread.currentThread().getState());
		
		
	}
}

输出为:

thread:Thread-1 start

thread:Thread-3 start

mainThread end:RUNNABLE

thread:Thread-2 start

thread:Thread-0 start

thread:Thread-1 end

thread:Thread-0 end

thread:Thread-3 end

thread:Thread-2 end


我们可以看到上面4个线程没有跑完,最后一句打印 就已经打印出来,那么我们如果想等4个线程执行完以后,后面的代码怎么办呢,就要使用CountDownLatch

请看修改后的代码

public class CountDownLatchDemo {

	public static void main(String[] args) throws InterruptedException {
		//初始化,入参count为需要等待执行的线程数
		CountDownLatch countDownLatch = new CountDownLatch(4);
		Runnable runnable = new Runnable() {
			Thread thread = Thread.currentThread();
			@Override
			public void run() {
				System.out.println("thread:"+thread.currentThread().getName()+" start");
				try {
					thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("thread:"+thread.currentThread().getName()+" end");
				//执行完线程,需要释放countDownLatch中的线程数
				countDownLatch.countDown();
			}
		};
		Thread thread1 = new Thread(runnable);
		Thread thread2 = new Thread(runnable);
		Thread thread3 = new Thread(runnable);
		Thread thread4 = new Thread(runnable);
		
		thread1.start();
		thread2.start();
		thread3.start();
		thread4.start();
		//执行等待命令
		countDownLatch.await();
		System.out.println("mainThread end:"+Thread.currentThread().getState());
		
		
	}
}
打印结果为:

thread:Thread-2 start

thread:Thread-0 start

thread:Thread-3 start

thread:Thread-1 start

thread:Thread-2 end

thread:Thread-1 end

thread:Thread-3 end

thread:Thread-0 end

mainThread end:RUNNABLE


达到我们预期的效果,这就是线程同步门闩的作用,需要注意的是构造方法传入的count数为等待线程数,就是说我们需要等待几个线程执行完,就传入几



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值