TimeInterval, 用于计算上次获取时间间隔的时间到当前时间的时间间隔
class="java">
非线程安全版本,用于1个线程里。
public class TimeInterval {
private long current;
public TimeInterval() {
current = System.currentTimeMillis();
}
public long get() {
long last = current;
current = System.currentTimeMillis();
return current - last;
}
}
----------------------------------------------------------------------------
线程安全版本,可以用于多个线程并发。
import java.util.concurrent.atomic.AtomicLong;
private final AtomicLong currentTimeHolder;
public TimeInterval() {
currentTimeHolder = new AtomicLong(System.currentTimeMillis());
}
public long get() {
long current = System.currentTimeMillis();
long last = currentTimeHolder.getAndSet(current);
return current - last;
}