
正文
JAVA版数据库主键ID生成器
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;public class sequence {
private static final long ONE_STEP = ;
private static final Lock LOCK = new ReentrantLock();
private static long lastTime = System.currentTimeMillis();
private static short lastCount = ;
private static int count = ; @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();
} catch (java.lang.InterruptedException e) {
}
continue;
} else {
lastTime = now;
lastCount = ;
done = true;
}
}
}
count = lastCount++;
}
finally
{
LOCK.unlock();
return lastTime+""+String.format("%03d",count);
}
}
public static void main(String[] args)
{
//测试
for(int i=;i<;i++)
{
System.out.println(nextId());
}
}
}
据说如果是用在集群环境,需要在前面加上机器的编号,或者IP。








