Skip to content

Instantly share code, notes, and snippets.

@zhugw
Created January 24, 2016 07:16
Show Gist options
  • Save zhugw/26938d33a61b376ca1a5 to your computer and use it in GitHub Desktop.
Save zhugw/26938d33a61b376ca1a5 to your computer and use it in GitHub Desktop.
验证并发情况下的自定义订单流水号生成器是否会有重复
// 验证并发情况下的自定义订单流水号生成器是否会有重复
// 订单流水号生成器
public static String getOrderNo(){
String orderNo = "";
String date = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
Integer math = new Random().nextInt(1000);
orderNo = date+""+math;
return orderNo;
}
// 验证代码
public static void main(String[] args) throws InterruptedException {
int nThreads = 60; //并发数
ExecutorService pool = Executors.newFixedThreadPool(nThreads);
final CountDownLatch latch = new CountDownLatch(nThreads);
final List<String> list = new CopyOnWriteArrayList<>(); //使用线程安全list 保存每次生成的订单流水号
for (int i = 0; i < nThreads; i++) {
pool.submit(new Runnable() {
@Override
public void run() {
String orderNo = getOrderNo();
list.add(orderNo);
latch.countDown();
}
});
}
latch.await(); //等待所有任务完成
System.out.println(list.size());
System.out.println(new HashSet<>(list).size()); //去重后的大小
Map<String, Long> countMap = list.stream().collect(Collectors.groupingBy(s->s,Collectors.counting()));
countMap.entrySet().forEach( e->{ //输出出现次数大于1次的订单流水号
if(e.getValue()>1L)
System.out.println(e.getKey() + " " +e.getValue());
});
}
@TamirTian
Copy link

时间+随机数,肯定会出现重复的

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment