设计思路及代码
将执行逻辑与计数逻辑封装到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