Java生成指定ビット数重複しない乱数
2382 ワード
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));
}
}
}