今天上班路上看微信公众号,看到一段比较好的代码,特意记录下来:
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class CurrentTimeMillisClock {
private volatile long now;
private CurrentTimeMillisClock() {
this.now = System.currentTimeMillis();
scheduleTick();
}
private void scheduleTick() {
new ScheduledThreadPoolExecutor
(1, runnable -> {
Thread thread = new Thread(runnable, "current-time-millis");
thread.setDaemon(true);
return thread;
}).scheduleAtFixedRate
(() -> now = System.currentTimeMillis(),
1,
1,
TimeUnit.MILLISECONDS
);
}
public long now() {
return now;
}
public static CurrentTimeMillisClock getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final CurrentTimeMillisClock INSTANCE = new CurrentTimeMillisClock();
}
}
使用 CurrentTimeMillisClock.getInstance().now()
代码来源:https://mp.weixin.qq.com/s/saD0Sd7DYDlyqgkjofPH2Q