【 Say little 】
Not much to say series, is direct liver, I believe we will understand, if the question of the students, meow ME!
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/ * * * *@author rs
*/
public class SystemClock {
private final int period;
private final AtomicLong now;
private static class InstanceHolder {
private static final SystemClock INSTANCE = new SystemClock(1);
}
private SystemClock(int period) {
this.period = period;
this.now = new AtomicLong(System.currentTimeMillis());
scheduleClockUpdating();
}
private static SystemClock instance(a) {
return InstanceHolder.INSTANCE;
}
private void scheduleClockUpdating(a) {
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "System Clock");
thread.setDaemon(true);
returnthread; }}); scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS); }private long currentTimeMillis(a) {
return now.get();
}
/** * replaces system.currentTimemillis () */
public static long now(a) {
return instance().currentTimeMillis();
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
for (long i = 0; i < Integer.MAX_VALUE; i++) {
SystemClock.now();
}
long end = System.currentTimeMillis();
System.out.println("SystemClock Time:" + (end - start) + "毫秒");
long start2 = System.currentTimeMillis();
for (long i = 0; i < Integer.MAX_VALUE; i++) {! [123.gif](https://upload-images.jianshu.io/upload_images/19662588-0e6edfd1236e6043.gif? imageMogr2/auto-orient/strip)
System.currentTimeMillis();
}
long end2 = System.currentTimeMillis();
System.out.println("currentTimeMillis Time:" + (end2 - start2) + "毫秒");
/ / SystemClock Time: 1450 milliseconds
/ / currentTimeMillis Time: 7482 milliseconds}}Copy the code
# While starting a single thread increases CPU usage, it is also an optimization point in high concurrency.
Welcome to pay attention to my wechat public number < search: Ting Yu notes >, will first some of the latest articles oh!
Thank you for reading this, if this article is well written and if you feel there is something to it
Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!
If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️