package com.hai.common.utils;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class IDGenerator {
	  
	    private static final long ONE_STEP = 10;
	    private static final Lock LOCK = new ReentrantLock();
	    private static long lastTime = System.nanoTime();
	    private static short lastCount = 0;
	    private static int count = 0;
	    /**
	     * 可传入指定长度的值
	     * @param length
	     * @return
	     */ 
	    @SuppressWarnings("finally")
	    public static String nextId(int... length) 
	    {
	        LOCK.lock();
	        try {
	            if (lastCount == ONE_STEP) {
	                boolean done = false;
	                while (!done) {
	                    long now = System.nanoTime();
	                    if (now == lastTime) {
	                        try {
	                            Thread.currentThread();
	                            Thread.sleep(1);
	                        } catch (InterruptedException e) {
	                        }
	                        continue;
	                    } else {
	                        lastTime = now;
	                        lastCount = 0;
	                        done = true;
	                    }
	                }
	            }
	            count = lastCount++;
	        }
	        finally 
	        {
	            LOCK.unlock();
	            String idStr = lastTime+""+String.format("%02d",count); 
	            if(length.length > 0 && length[0] > 0){
	            	idStr = idStr.substring(idStr.length()-length[0]<0?0:idStr.length()-length[0], idStr.length());
	            }
	            return idStr;
	        }
	    }
	    public static void main(String[] args)
	    {
//	        for(int i=0;i<100;i++)
//	        {
//	            System.out.println(nextId());
//	        }        
//	        nextId(20);
	    	System.out.println(System.currentTimeMillis());
	    }
	
}
