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

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));
        }

    }

}

你可能感兴趣的:(Java)