随机生成序列号

import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class IDGenerator
{
  private static SecureRandom r1 = new SecureRandom();

  private static SecureRandom r2 = new SecureRandom();

  private static SecureRandom r3 = new SecureRandom();

  private static SecureRandom r4 = new SecureRandom();

  private static final Long L1 = Long.valueOf(1000000000L);
  private static final Long L2 = Long.valueOf(1000000L);
  private static final Long L3 = Long.valueOf(1000L);
  private static long beginMillis;

  static
  {
    try
    {
      beginMillis = new SimpleDateFormat("yyyyMMdd HH:mm:ss").parse("20100101 00:00:00").getTime();
    }
    catch (ParseException localParseException)
    {
      beginMillis = System.currentTimeMillis();
    }
  }

  public long getID20()
  {
    long timeValue = System.currentTimeMillis() / 1000L;
    int randomValue1 = Math.abs(r1.nextInt() % 1000);
    int randomValue2 = Math.abs(r2.nextInt() % 1000);
    int randomValue3 = Math.abs(r3.nextInt() % 1000);
    return timeValue * L1.longValue() + randomValue1 * L2.longValue() + randomValue2 * L3.longValue() + randomValue3;
  }

  public int getID10()
  {
    int randomNum;
    do
      randomNum = r4.nextInt(20);
    while ((randomNum == 0) || (randomNum == 2) || (randomNum == 4) || (randomNum == 6) || (randomNum == 8));

    return randomNum * 100000000 + (int)((System.currentTimeMillis() - beginMillis) / 1000L % 100000000L);
  }
}

你可能感兴趣的:(Java)