java怎么生成一个一天内不会重复的20位流水号

2025-05-19 16:39:49
推荐回答(4个)
回答1:

我为您写了 一遍,望采纳。

package Zxing;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
 * 
 * 开发公司:SOJSON在线工具 


 * 版权所有:© www.sojson.com
 * 博客地址:http://www.sojson.com/blog/
 * 


 * 
 * Demo
 * 
 * 


 * 
 * 区分 责任人 日期    说明

 * 创建 周柏成 2017年4月11日 09:43  

 *
 * @author zhou-baicheng
 * @email  so@sojson.com
 * @version 1.0,2017年4月11日 09:43 

 * 
 */
public class Demo {

    public static void main(String[] args) {
        //格式化当前时间
        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = sfDate.format(new Date());
        //得到17位时间如:20170411094039080
        System.out.println("时间17位:" + strDate);
        //为了防止高并发重复,再获取3个随机数
        String random = getRandom620(3);
        
        //最后得到20位订单编号。
        System.out.println("订单号20位:" + strDate + random);
        
    }
    /**
     * 获取6-10 的随机位数数字
     * @param length    想要生成的长度
     * @return result
     */
    public static String getRandom620(Integer length) {
        String result = "";
        Random rand = new Random();
        int n = 20;
        if (null != length && length > 0) {
            n = length;
        }
        int randInt = 0;
        for (int i = 0; i < n; i++) {
            randInt = rand.nextInt(10);

            result += randInt;
        }
        return result;
    }
}

回答2:

public class Task2 {
static double te=10000000;//一天是24*60*60最多5位数,这里定8位
static String s="ABCDEFGHIJKL";//12位
public static void main(String[] args) {

TimerTask task = new TimerTask() {
@Override
public void run() {
// task to run goes here
te++;
System.out.println(s+te);
}
};
Timer timer = new Timer();
long delay = 0;
long intevalPeriod = 1 * 1000; //一秒触发一次
// schedules the task to be run in an interval
timer.scheduleAtFixedRate(task, delay, intevalPeriod);
} // end of main

}
多个想法。随便看看

回答3:

希望对你有帮助!获取当前时间毫秒数,如果是单线程的话,一定无重复 一般这样在多线程并发中取到相同毫秒的概率都几乎为0,基本可以保证无重复

回答4:

Random random = new Random();
String name = System.currentTimeMillis() + String.valueOf( (Math.abs(random.nextLong())) );