利用CountDownLatch自制计数器

自定义计数器

@Slf4j
@Component
public final class Monitor {
    private static final AtomicInteger COUNTER = new AtomicInteger();
    private static CountDownLatch latch = new CountDownLatch(1);


    /**
     * @param limit        限制总数
     * @param currentCount 当前计数
     */
    public static void control(int limit, int currentCount) {
        if (COUNTER.addAndGet(currentCount) >= limit) {
            latch = new CountDownLatch(1);
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

 

    @Scheduled(fixedRate = 1000)
    public void record() {
        COUNTER.getAndSet(0);
        latch.countDown();
    }
}

 

你可能感兴趣的:(Java)