学堂 学堂 学堂公众号手机端

java 实现满足一定数量超过一定时间后才做任务的队列

lewis 1年前 (2024-04-10) 阅读数 8 #技术
@Slf4j
public class EventDelayQueueService {

    private final List<TaskInfo> items = Collections.synchronizedList(new ArrayList<>());
    private final int maxCapacity = 500;
    private final ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(1);;
    private final MDCThreadPoolExecutor executor = Executors.newFixedThreadPool(5);;
    private final AtomicInteger count = new AtomicInteger(0);

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("start the EventDelayQueueService .");
        scheduled.scheduleAtFixedRate(() -> {
            if (items.size() > maxCapacity) {
                asyncAction();
                return;
            }
            if (count.incrementAndGet() > 10) {
                asyncAction();
            }
        },10,200, TimeUnit.MILLISECONDS);
    }

    private void asyncAction() {
        // TODO
    }


    public void add(TaskInfo info) {
        items.add(info);
    }
}

版权声明

本文仅代表作者观点,不代表博信信息网立场。

热门