java毫秒级抖动怎么处理_用Java实现去抖动

小编典典

请考虑以下线程安全解决方案。请注意,锁定粒度是在密钥级别上的,因此仅同一密钥上的调用会相互阻塞。它还处理在调用call(K)时发生的密钥K过期的情况。

public class Debouncer {

private final ScheduledExecutorService sched = Executors.newScheduledThreadPool(1);

private final ConcurrentHashMap delayedMap = new ConcurrentHashMap();

private final Callback callback;

private final int interval;

public Debouncer(Callback c, int interval) {

this.callback = c;

this.interval = interval;

}

public void call(T key) {

TimerTask task = new TimerTask(key);

TimerTask prev;

do {

prev = delayedMap.putIfAbsent(key, task);

if (prev == null)

sched.schedule(task, interval, TimeUnit.MILLISECONDS);

} while (prev != null && !prev.extend()); // Exit only if new task was added to map, or existing task was extended successfully

}

public void terminate() {

sched.shutdownNow();

}

// The task that wakes up when the wait time elapses

private class TimerTask implements Runnable {

private final T key;

private long dueTime;

private final Object lock = new Object();

public TimerTask(T key) {

this.key = key;

extend();

}

public boolean extend() {

synchronized (lock) {

if (dueTime < 0) // Task has been shutdown

return false;

dueTime = System.currentTimeMillis() + interval;

return true;

}

}

public void run() {

synchronized (lock) {

long remaining = dueTime - System.currentTimeMillis();

if (remaining > 0) { // Re-schedule task

sched.schedule(this, remaining, TimeUnit.MILLISECONDS);

} else { // Mark as terminated and invoke callback

dueTime = -1;

try {

callback.call(key);

} finally {

delayedMap.remove(key);

}

}

}

}

}

2020-09-15

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值