Java生成订单号/交易流水号
分析:既然是订单号/交易流水号,首先是不能重复,其次需考虑到性能问题。
设计如下:
"HF"+时间戳+随机数+循环数
代码如下:
1 int x = 1000; 2 for(int i=0;i<10;i++){ 3 x+=1; 4 System.out.println("HF"+System.currentTimeMillis()+RandomUtils.getNo(2)+x); 5 }
其中:RandomUtils类
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 package com.test.common.util; 2 3 import org.apache.commons.lang.RandomStringUtils; 4 5 public class RandomUtils 6 { 7 private static String randString = ""; 8 9 public synchronized static String getNo(int k) 10 { 11 if (randString.length() > 20000) 12 { 13 randString = ""; 14 } 15 String rno = getNoNo(k); 16 while (randString.indexOf(rno + ",") >= 0) 17 { 18 rno = getNoNo(k); 19 } 20 randString += rno + ","; 21 return rno; 22 } 23 24 private static String getNoNo(int k) 25 { 26 try 27 { 28 Thread.sleep(1); 29 } 30 catch (InterruptedException e) 31 { 32 e.printStackTrace(); 33 } 34 return RandomStringUtils.randomNumeric(k); 35 } 36 }