美文网首页Java 核心技术
一个简单的System.currentTimeMillis()居

一个简单的System.currentTimeMillis()居

作者: rs汀 | 来源:发表于2020-03-02 18:55 被阅读0次
    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() {
            return InstanceHolder.INSTANCE;
        }
    
        private void scheduleClockUpdating() {
            ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
                @Override
                public Thread newThread(Runnable runnable) {
                    Thread thread = new Thread(runnable, "System Clock");
                    thread.setDaemon(true);
                    return thread;
                }
            });
            scheduler.scheduleAtFixedRate(() -> now.set(System.currentTimeMillis()), period, period, TimeUnit.MILLISECONDS);
        }
    
        private long currentTimeMillis() {
            return now.get();
        }
    
        /**
         * 用来替换原来的System.currentTimeMillis()
         */
        public static long now() {
            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://img.haomeiwen.com/i19662588/0e6edfd1236e6043.gif?imageMogr2/auto-orient/strip)
    
                System.currentTimeMillis();
            }
            long end2 = System.currentTimeMillis();
            System.out.println("currentTimeMillis Time:" + (end2 - start2) + "毫秒");
            //SystemClock Time:1450毫秒
            //currentTimeMillis Time:7482毫秒
        }
    }
    

    虽然单独启动了一个线程,增加了cpu使用率,但是在高并发当中也是一个优化点。 123.gif

    相关文章

      网友评论

        本文标题:一个简单的System.currentTimeMillis()居

        本文链接:https://www.haomeiwen.com/subject/dbjbkhtx.html