随机数字工具类

示例代码:

import java.math.BigDecimal;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 随机数字工具类
 */
public final class RandomNumberUtil {

    private static AtomicLong id;

    /**
     * 简单生成Long类型, 大数据量下无法做到唯一
     */
    public synchronized static Long getId() {
        Long time = Long.valueOf(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())) * 10000;
        if (id == null) {
            id = new AtomicLong(time);
            return id.get();
        }
        if (time <= id.get()) {
            id.addAndGet(1);
        } else {
            id = new AtomicLong(time);
        }
        return id.get();
    }

    /**
     * 生成[1, max]的随机值
     *
     * @param max
     * @return
     */
    public static Integer randomRange(Integer max) {
        SecureRandom rm = new SecureRandom();
        rm.setSeed(getId());
        return rm.nextInt(max) + 1;
    }

    /**
     * 生成[min, max]的随机值
     *
     * @param min
     * @param max
     * @return
     */
    public static Integer randomRange(Integer min, Integer max) {
        SecureRandom rm = new SecureRandom();
        rm.setSeed(getId());
        return rm.nextInt(max) + min;
    }

    /**
     * 随机生成指定范围BigDecimal
     */
    public static BigDecimal randomBigDecimal(float minF, float maxF) {
        //生成随机数
        BigDecimal db = new BigDecimal(Math.random() * (maxF - minF) + minF);
        //返回保留两位小数的随机数。不进行四舍五入
        return db.setScale(2, BigDecimal.ROUND_UP);
    }

    /**
     * 随机生成指定范围BigDecimal
     */
    public static BigDecimal randomBigDecimal(float minF, float maxF, int bits) {
        //生成随机数
        BigDecimal db = new BigDecimal(Math.random() * (maxF - minF) + minF);
        //返回保留两位小数的随机数。不进行四舍五入
        return db.setScale(bits, BigDecimal.ROUND_UP);
    }

    public static void main(String[] args) throws InterruptedException {
        Set<Long> set = new TreeSet<>();
        for (int i = 0; i < 100; i++) {
            new Thread(() ->
            {
                Long id = getId();
                set.add(id);
                System.out.println(Thread.currentThread().getName() + ":" + id);
            }
            ).start();
        }
        Thread.sleep(5000);
        int size = set.size();
        System.out.println(size);
    }
}

 

posted @ 2022-06-09 15:33  残城碎梦  阅读(91)  评论(0编辑  收藏  举报