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

java 生成 序列号 随机字符串等

2014-10-23 11:40 417 查看
生成序列号尤其要注意的是高并发时候序列号重复和抢占带来的唯一ID问题:

private static int maxvaluefive=99999999;
private static int minvaluefive=0;
private static AtomicInteger atomic = new AtomicInteger(minvaluefive);
/**  生成序列号 */
static String getSeqFive(int coverPad) {
for (;;) {
int current = atomic.get();
int newValue = current >= maxvaluefive ? minvaluefive : current + 1;
if (atomic.compareAndSet(current, newValue)) {
return StringUtils.leftPad(String.valueOf(current), coverPad, "0");
}
}
}


使用的时候可以与时间以及其他业务编号结合使用保证序列的唯一性:比如生成订单号,流水号等

private static Random strGen = new Random();;
private static Random numGen = new Random();;
private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();;
private static char[] numbers = ("0123456789").toCharArray();;
/** * 产生随机字符串 * */
public static final String randomString(int length) {
if (length < 1) {
return null;
}
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[strGen.nextInt(61)];
}
return new String(randBuffer);
}

/** * 产生随机数值字符串 * */
public static final String randomNumStr(int length) {
if (length < 1) {
return null;
}
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbers[numGen.nextInt(9)];
}
return new String(randBuffer);
}


方便随手使用

原文链接 http://blog.csdn.net/zl378837964/article/details/40394459
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: