您的位置:首页 > 编程语言 > Java开发

Java生成指定位数不重复随机数

2017-05-21 19:50 751 查看
1、以生成不重复20位随机数为例

public class SerialGeneratorTest {

private static final Object OBJECT = new Object();
private static long bIndex = 0;

/**
* 可用多线程检测是否会产生相同随机数
* @param length
* @return
*/
public static String createSerialNo(int length) {
double max = Math.pow(10, length);
String curSerial;
synchronized (OBJECT) {
if (++bIndex >= max){
bIndex = 0;
}
curSerial = bIndex + "";
}
while (curSerial.length() < length) {
curSerial = "0" + curSerial;
}
return curSerial;
}

@Test
public void testCreateSerialNo() throws Exception {

for (int i = 0; i < 2; i++) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String now = sdf.format(new Date());
System.out.println(now + createSerialNo(4));
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: