达到阈值自动执行的工具类

设计思路及代码
将执行逻辑与计数逻辑封装到ThresholdCounter,而不是耦合在ThresholdCounterTest业务代码中

package xyz.yq56.easytool.utils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import lombok.extern.slf4j.Slf4j;

/**
 * @author yiqiang
 * @date 2022/11/22 14:45
 */
@Slf4j
public class ThresholdCounterTest {

    private ThresholdCounterTest() {
    }


    public static void main(String[] args) {
        ThresholdCounter counter = new ThresholdCounter(2,
                                                        () -> log.info("执行逻辑"));

        List<String> roomIds = Arrays.asList("1", "5", "6");

        for (int i = 0; i < roomIds.size(); i++) {
            log.info("当前: " + (i + 1));
            counter.incr();
        }
    }

    /**
     * 计数器,达到阈值就执行
     */
    public static class ThresholdCounter {

        private final AtomicInteger count = new AtomicInteger(0);

        private final int threshold;

        Processor processor;

        public ThresholdCounter(int threshold, Processor processor) {
            this.threshold = threshold;
            this.processor = processor;
        }

        public void incr() {
            incr(1);
        }

        public void incr(int delta) {
            int nowCount = count.addAndGet(delta);
            if (nowCount == threshold) {
                log.info("ThresholdCounter | 达到阈值,自动执行 | newCount: {},threshold: {}",
                         nowCount, threshold);
                processor.process();
            }
        }
    }

    @FunctionalInterface
    interface Processor {
        /**
         * 执行
         */
        void process();
    }

}

运行结果

03:24:28.225 [main] INFO xyz.yq56.easytool.utils.ThresholdCounterTest - 当前: 1
03:24:28.227 [main] INFO xyz.yq56.easytool.utils.ThresholdCounterTest - 当前: 2
03:24:28.227 [main] INFO xyz.yq56.easytool.utils.ThresholdCounterTest$ThresholdCounter - ThresholdCounter | 达到阈值,自动执行 | newCount: 2,threshold: 2
03:24:28.228 [main] INFO xyz.yq56.easytool.utils.ThresholdCounterTest - 执行逻辑
03:24:28.228 [main] INFO xyz.yq56.easytool.utils.ThresholdCounterTest - 当前: 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值