CountDownLatch的简单使用

个人理解就是当指定数量的线程全部执行完毕后再进行下一步动作

package study;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Test {
	public static class myThread extends Thread {
		int sleepSeconds;
		CountDownLatch countDownLatch;
		public myThread(String name,int seconds,CountDownLatch countDownLatch) {
			this.setName(name);
			this.sleepSeconds = seconds;
			this.countDownLatch = countDownLatch;
		}
		@Override
		public void run() {
			long startTime = System.currentTimeMillis();
			System.out.println(this.getName() + "开始执行");
			try {
				TimeUnit.SECONDS.sleep(sleepSeconds);
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				countDownLatch.countDown();
			}
			
			long endTime = System.currentTimeMillis();
			System.out.println(this.getName() + "结束执行,耗时:" + String.valueOf(endTime - startTime));
		}
	}
	
	public static void main(String[] args) throws InterruptedException {
		CountDownLatch countDownLatch = new CountDownLatch(3);
		long start = System.currentTimeMillis();
		System.out.println("------主线程开始------");
		myThread t3 = new myThread("线程3", 3,countDownLatch);
		t3.start();
		myThread t1 = new myThread("线程1", 2,countDownLatch);
		t1.start();
		myThread t2 = new myThread("线程2", 5,countDownLatch);
		t2.start();
		countDownLatch.await();
		long end = System.currentTimeMillis();
		System.out.println("主线程执行完毕,耗时:" + String.valueOf(end - start));
	}
}

这个实现了类似上一篇文章的join效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值