欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java基础之生成不重复的数作为数据库表主键(18位)

程序员文章站 2022-03-03 20:03:07
...
package org.random;

import java.util.Date;
import java.util.Random;

public class SeedUtil {
	private static Long randomNumber;
	private static Long curIndex = Long.valueOf(0L);

	public SeedUtil() {
	}

	public synchronized static Long getId() throws Exception {
		Long index = null;
		// 从0到999 curIndex*100 curIndex 100-99900
		index = (curIndex = curIndex.longValue() + 1L).longValue() % 1000L;
		if (curIndex.longValue() >= 1000L) {
			curIndex = 0L;
		}
		// 随机数 1-10
		randomNumber = Long.valueOf(new Random().nextInt(100));
		return (new Date()).getTime() * 100000L + index.longValue() * 100L
				+ randomNumber.longValue();
	}

}