Java获取随机数、随机字符串(五种方法)

目录

一、Math.random()

二、Random

三、ThreadLocalRandom

四、System.currentTimeMillis()

五、UUID


一、Math.random()

Math.random():获取double类型的小数范围 [0.0,1.0)

  • 线程安全
  • 最常用

获取[max,min]之间的随机数公式:

(int)(Math.random()*(max - min - 1) + min)

假设max为3,min为1
当Math.random()取得最小随机数时,结果为0*(3 - 1 + 1) + 1 = 1
当Math.random()取得最大随机数时,结果 > 1*(3 - 1 + 1) + 1 ≈ 3.99999,进行强制类型转换之后得3

public static void getRandomByMathRandom(){
        int max = 3;
        int min = 1;
        int temp = (int)(Math.random()*(max - min + 1) + min);
        System.out.println(temp);
    }

二、Random

Random类中的nextInt():获取[0, max)之间的随机整数

  • 线程安全
  • 非加密安全(加密安全推荐使用:SecureRandom)
new Random().nextInt(max);

注:类似的可以调用nextLong(),nextDouble(),nextFloat()……

public static void getRandomByRandom(){
        int max = 3;
        int temp = new Random().nextInt(max);
        System.out.println(temp);
    }

三、ThreadLocalRandom

ThreadLocalRandom:与当前线程隔离的随机数生成器。(从jdk1.7版本开始)

  • 多线程时推荐使用

获取[min,max)之间的随机数代码

int temp = ThreadLocalRandom.current().nextInt(min, max);

注:类似的可以调用nextLong(),nextDouble()……

public static void getRandomByThreadLocalRandom(){
        int max = 5;
        int min = 1;
        int temp = ThreadLocalRandom.current().nextInt(min, max);
        System.out.println(temp);
    }

四、System.currentTimeMillis()

System.currentTimeMillis():返回当前时间

  • 其实没什么优点,不推荐使用

获得[min,max)之间的随机整数

int temp = (int)(System.currentTimeMillis() % (max - min) + min);
public static void getRandomByCurrentTimeMillis(){
        int max = 5;
        int min = 2;
        long temp = System.currentTimeMillis();
        int random = (int)(temp % (max - min) + min);
        System.out.println(random);
    }

五、UUID

UUID:表示一个可变的通用唯一标识符

  • 加密安全

生成随机字符串:

String temp = UUID.randomUUID().toString();
public static void getRandomByUUID(){
        String temp = UUID.randomUUID().toString();
        System.out.println(temp);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章