CountDownLatch

目录

文章目录

一、CountDownLatch是什么?

二、使用CountDownLatch

一、CountDownLatch是什么?

CountDownLatch中count down是倒数的意思,latch则是门闩的含义。整体含义可以理解为倒数的门栓,似乎有一点“三二一,芝麻开门”的感觉。CountDownLatch的作用也是如此,在构造CountDownLatch的时候需要传入一个整数n,在这个整数“倒数”到0之前,主线程需要等待在门口,而这个“倒数”过程则是由各个执行线程驱动的,每个线程执行完一个任务“倒数”一次。总结来说,CountDownLatch的作用就是等待其他的线程都执行完任务,必要时可以对各个任务的执行结果进行汇总,然后主线程才继续往下执行。

二、使用CountDownLatch

创建:

new CountDownLatch(倒数的数字) 

主要方法:

void countDown() 倒数一次,数字减一
void await() 阻塞当前线程,当倒数为0就唤醒

代码如下(示例):

public class CountDownLatchDemo {

    public static void main(String[] args) {
        //创建倒数对象
        CountDownLatch latch = new CountDownLatch(3);
        new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"在等待其它线程!!");
            try {
                //等待其它线程结束
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" finished!!");
        }).start();
        for (int j = 0; j < 3; j++) {
            new Thread(()->{
                for(int i = 0;i < 5;i++){
                    System.out.println(Thread.currentThread().getName()+"-->"+i);
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                //倒数一次
                latch.countDown();
                System.out.println(Thread.currentThread().getName()+" finished,count=" + latch.getCount());
            }).start();
        }
    }

Semaphore 类

信号量,控制启动线程的数量

创建:

new Semaphore(最大数量)

常见使用方法:

aquired() 请求一个信号量
release() 释放一个信号量
public class SemaphoreDemo {

    public static void main(String[] args) {
        //创建信号量
        Semaphore semaphore = new Semaphore(5);
        for(int i = 0;i < 100;i++){
            //启动线程
            new Thread(() -> {
                try {
                    //请求信号量
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"启动了");
                    Thread.sleep(1000);
                    //释放信号量
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值