@FunctionalInterface public interface Throttle { /** * @param callback 回调函数 * @param delay 流速控制时间,单位毫秒 * @return 使用lambda和闭包构造的匿名节流阀对象 */ static Throttle build(Throttle callback, long delay) { AtomicLong startTime = new AtomicLong(System.currentTimeMillis()); AtomicReference<Thread> thread = new AtomicReference<>(); return () -> { final long currentTime = System.currentTimeMillis(); synchronized (callback) { if (thread.get() != null) thread.get().interrupt(); if (currentTime - startTime.get() >= delay) { callback.callback(); startTime.set(currentTime); } else { thread.set(new Thread(() -> { try { Thread.sleep(delay); } catch (InterruptedException ignored) { return; } callback.callback(); })); thread.get().start(); } } }; } /** * 执行节流阀 */ void callback(); }
Throttle throttle = Throttle.build(new Throttle() { @Override public void callback() { Log.e(TAG, "真正执行方法"); executeMethod("1"); } }, 2000);
tvLeft1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { throttle.callback(); } });