Java基础知识之随机数

一.随机数
①.Random类
Random类用于生产一个伪随机数(通过相同的种子,产生的随机数是相同的)。
public Random():使用默认的种子(以当前系统时间作为种子)。
public Random(long seed):根据指定的种子。

public class RandomDemo {
    public static void main(String[] args) {
        Random random =new Random();
        int num = random.nextInt(100);
        System.out.println(num);
    }
}

②ThreadLocalRandom类
ThreadLocalRandom是Java7新增类,是Random类的子类,在多线程并发情况下,ThreadLocalRandom相对于Random可以减少多线程资源竞争,保证了线程的安全性。
因为构造器是默认访问权限,只能在java.util包中创建对象,故,提供了一个方法ThreadLocalRandom.current()用于返回当前类对象.

public class ThreadLocalRandomDemo {
    public static void main(String[] args) {
        ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
        //可直接生成指定范围内的随机数
        int num = threadLocalRandom.nextInt(10, 100);
        System.out.println(num);
    }
}

③UUID类
通用惟一识别:Universally Unique Identifier; 在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的。
UUID是一个128位长的数字,一般用16进制表示。算法的核心思想是结合机器的网卡、当地时间、一个随即数来生成UUID.
我们一般用来表示:随机的唯一的字符串.

public class UUIDDemo {
    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);
    }
}

验证码的生成
①生成由数字和字母组成的验证码

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class RandomTest {
    public static void main(String[] args) {
        String[] beforeShuffle = new String[]{"0","1","2", "3", "4", "5", "6", "7",
                "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z"};
        List list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        System.out.println(afterShuffle);
        String result = afterShuffle.substring(5, 11);
        System.out.print(result);
    }
}

②生成只由数字组成的验证码

 System.out.println((int)((Math.random()*9+1)*100000));
发布了99 篇原创文章 · 获赞 2 · 访问量 2624

猜你喜欢

转载自blog.csdn.net/weixin_41588751/article/details/105127837