import Java.util.concurrent.locks.lock;import java.util.concurrent.locks.ReentrantLock; Public classSequence {Private StaticFinalLongOne_step =Ten; Private StaticFinal Lock lock =NewReentrantlock (); Private Static LongLasttime =System.currenttimemillis (); Private Static ShortLastCount =0; Private Static intCount =0; @SuppressWarnings ("finally") Public StaticString NextID () {LOCK.Lock(); Try { if(LastCount = =one_step) {Boolean done=false; while(!Done ) { Longnow =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 (); returnlasttime+""+string.format ("%03d", Count); } } Public Static voidMain (string[] args) {//Test for(intI=0;i< +; i++) {System. out. println (NextID ()); } }}
It is said that if it is used in a clustered environment, it needs to be preceded by a machine number, or IP.
Java Edition database primary key ID generator