zoukankan      html  css  js  c++  java
  • JAVA版数据库主键ID生成器

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class sequence {
        private static final long ONE_STEP = 10;
        private static final Lock LOCK = new ReentrantLock();
        private static long lastTime = System.currentTimeMillis();
        private static short lastCount = 0;
        private static int count = 0;
    
        @SuppressWarnings("finally")
        public static String nextId() 
        {
            LOCK.lock();
            try {
                if (lastCount == ONE_STEP) {
                    boolean done = false;
                    while (!done) {
                        long now = System.currentTimeMillis();
                        if (now == lastTime) {
                            try {
                                Thread.currentThread();
                                Thread.sleep(1);
                            } catch (java.lang.InterruptedException e) {
                            }
                            continue;
                        } else {
                            lastTime = now;
                            lastCount = 0;
                            done = true;
                        }
                    }
                }
                count = lastCount++;
            }
            finally 
            {
                LOCK.unlock();
                return lastTime+""+String.format("%03d",count); 
            }
        }
        public static void main(String[] args)
        {
            //测试
            for(int i=0;i<1000;i++)
            {
                System.out.println(nextId());
            }        
        }
    }

    据说如果是用在集群环境,需要在前面加上机器的编号,或者IP。

  • 相关阅读:
    hadoop中map和reduce的数量设置问题
    Flink基础
    Leetcode中的SQL题目练习(二)
    Redis-2- 基本概念
    Redis-1-安装
    C#事件(1)
    java(13)内部类
    java(12)异常处理
    java(11)构造器
    java(10)接口抽象类
  • 原文地址:https://www.cnblogs.com/littlehb/p/3946097.html
Copyright © 2011-2022 走看看