多线程设计模式——二十二、Latch设计模式

Latch(阀门)设计模式也叫做 Count Down 设计模式。当若干个线程并发执行完某个特 定的任务,然后等到所有的子任务都执行结束之后再统一汇总。

CountDownLatch 能够使一个线程在等待另外一些线程完成各自工作之后,再继续执 行。使用一个计数器进行实现。计数器初始值为线程的数量。当每一个线程完成自己任务后, 计数器的值就会减一。当计数器的值为 0 时,表示所有的线程都已经完成了任务,然后在 CountDownLatch 上等待的线程就可以恢复执行任务。示例代码如下:

代码1:封装自己的CountDownLatch

package com.bjsxt.chapter22;


public class CustomCountDownLatch {
   
    private volatile int count;
    public CustomCountDownLatch(int count){
   
        this.count=count;
    }
    public void countDown(){
   
        synchronized (this){
   
            this.count--;
            System.out.println(Thread.currentThread().getName()+" will end.");
            this.notifyAll();// 只会唤醒 main线程
        }
    }
    public void await(){
   
        synchronized (this){
   
            try{
   
                while(count!=0){
   
                    System.out.println(Thread.currentThread().getName()+" will wait.");// 被唤醒了5次
                    this.wait();
                    System.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值