Id解析处理工具类

JAVA修炼塔 Q群号:535296702 欢迎追求技术巅峰的有志之士加入探讨!!!!!

package com.util;
/**
* 获取主键ID,使用时间+计数器方式实现
* @author King
*
*/
public class IdUtils {

public static IdUtils instance = null;

private static final long ONE_STEP = 100;
private static long lastTime = System.currentTimeMillis();
private static short count = 0;

/**
* 获取单例对象
* @return
*/
public synchronized static IdUtils getInstanse(){
   if(instance == null){
    instance = new IdUtils();
   }
   return instance;
}

private IdUtils(){
}
/**
* 根据对象获取表主键
* @param clazz
* @return
*/
public synchronized String getUID(){
   try{
    if (count == ONE_STEP) {
     boolean done = false;
     while (!done) {
      long now = System.currentTimeMillis();
      if (now == lastTime) {
       try {
        Thread.sleep(1);
       } catch (java.lang.InterruptedException e) {
       }
       continue;
      } else {
       lastTime = now;
       count = 0;
       done = true;
      }
     }
    }
   }catch(Exception e){
    e.printStackTrace();
   }
   String result = lastTime + "" + (count++);
   return result;
}
    public static void main(String[] args) {
    
        System.out.println(IdUtils.getInstanse().getUID());
    }
}

 

posted @ 2017-01-11 11:36  烟雨观春柳  阅读(128)  评论(0)    收藏  举报