Debouncer类
import java.util.concurrent.*;
public class Debouncer {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final ConcurrentHashMap<Object, Future<?>> delayedMap = new ConcurrentHashMap<>();
public void debounce(final Object key, final Runnable runnable, long delay, TimeUnit unit) {
if (!delayedMap.containsKey(key)) {
delayedMap.putIfAbsent(key, scheduler.schedule(() -> {
try {
runnable.run();
} finally {
delayedMap.remove(key);
}
}, delay, unit));
}
}
public void shutdown() {
scheduler.shutdownNow();
}
}
测试
@Test
public void debouncer() throws InterruptedException {
Debouncer debouncer = new Debouncer();
for (int i = 0; i < 10; i++) {
System.out.println("start---------" + System.currentTimeMillis());
debouncer.debounce("test_key",
() -> {System.out.println("run ----------" + System.currentTimeMillis());},
1, TimeUnit.SECONDS);
}
Thread.sleep(8000);
}