java产生随机数的三种方式

public class Test {
    public static void main(String[] args) {
        /**
         *Random类:
         * 创建随机数对象有2种,一种是添加参数,也叫种子,这种方式创建出来的数,刷新后不会改变,相当于常量了
         * 主要方法: nextInt(int n)产生0到n之间的随机数;nextDouble(),产生0到1之间的随机数,Math.random()底层调用的是该方法nextDouble()
         *
         */
        Random random = new Random(2);
        System.out.println(random.nextInt());//产生的随机数刷新后不会改变

        Random r2 = new Random();
        System.out.println(r2.nextInt(10));//10以内的随机数
        System.out.println(r2.nextDouble());//0到1之间的随机数

        /**
         *TreadLocalRandom
         1.该对象是random 的子类;
         2.创建对象:ThreadLocalRandom random=ThreadLocalRandom.current();
         3.random.nextInt(a,b),产生a到b之间的随机数
         */
        ThreadLocalRandom current = ThreadLocalRandom.current();
        System.out.println(current.nextInt(2, 8));//2到8之间的随机数
        System.out.println(current.nextInt(5));//5以内的随机数
        System.out.println(current.nextInt());//随机整数

        /**
         *UUID号称2000年不重复的产生随机字符串的方法,很多公司用来做业务唯一主键的生成
         *
         */
        System.out.println(UUID.randomUUID().toString());
        System.out.println(UUID.randomUUID().toString().replaceAll("-",""));//32个字符



    }
}

 

posted @ 2019-06-04 16:18  yangxiaohui227  阅读(445)  评论(0编辑  收藏  举报