java9 coutdown_Java深入学习08:CountDownLatch应用

Java深入学习08:CountDownLatch应用

一、CountDownLatch是什么

A synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.

CountDownLatch是一个同步助手,它允许一个或多个线程在在其他线程中执行的一组操作完成前,一直处于等待状态。

二、案例

public class CountDownLatchTest {

public static void main(String[] args) {

CountDownLatch latch = new CountDownLatch(100);

CountDownLatchThread th = new CountDownLatchThread(latch);

long start = System.currentTimeMillis();

for(int i = 0; i< 100; i++){

new Thread(th).start();

}

try {

latch.await();

} catch (InterruptedException e) {

e.printStackTrace();

}

long end = System.currentTimeMillis();

System.out.println("一共花费:" + (end - start) + " 毫秒");

}

}

class CountDownLatchThread implements Runnable{

private CountDownLatch latch ;

public CountDownLatchThread(CountDownLatch latch){

this.latch = latch;

}

@Override

public void run() {

try {

System.out.println(Thread.currentThread().getName()+"完成任务");

} finally {

//计数减1

latch.countDown();

}

}

}

日志输出

Thread-0完成任务

Thread-5完成任务

Thread-4完成任务

Thread-3完成任务

Thread-2完成任务

Thread-1完成任务

.......

Thread-97完成任务

Thread-99完成任务

一共花费:11 毫秒

Process finished with exit code 0

三、CountDownLatch主要方法

//计数

//Decrements the count of the latch, releasing all waiting threads if the count reaches zero.

public void countDown() {

sync.releaseShared(1);

}

//等待

//the current thread to wait until the latch has counted down to zero

public void await() throws InterruptedException {

sync.acquireSharedInterruptibly(1);

}

四、应用场景

当一个主任务中,有多个子任务可以同时进行(多个线程),最有有一个或多个子任务,需要在前面的任务全部完成后才可以执行,那么就可以用CountDownLatch实现"在前面的任务全部完成后才可以执行"

标签:Java,Thread,08,任务,完成,CountDownLatch,latch,public

来源: https://www.cnblogs.com/wobuchifanqie/p/12512337.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值