伪随机数生成

Random类专门用于生成一个伪随机数,它有两个构造器:一个构造器使用默认的种子(以当前时间为种子),另一个构造器需要程序员输入一个long型整数的种子。

ThreadLocalRandom类是Java 7新增的一个类它是Random增强版。在并发访问的环境下,使用ThreadLocalRandom来代替Random可以减少多线程资源竞争,最终保证系统具有更好的线程安全性。

package com.gdut.basic;

import java.util.Arrays;
import java.util.Random;

public class RandomTest {

    public static void main(String[] args) {
        Random  rand = new Random();
        System.out.println("rand.nextBoolean():"+rand.nextBoolean());
        byte[] buffer = new byte[16];
        rand.nextBytes(buffer);
        System.out.println(Arrays.toString(buffer));
        //生成0.0~1.0之间的double伪随机数
        System.out.println("rand.nextDouble():"+rand.nextDouble());
        //生成0.0~1.0之间的float伪随机数
        System.out.println("rand.nextFloat():"+rand.nextFloat());
        //生成平均值0.0,标准差是1.0的伪高斯数
        System.out.println("rand.nextGaussian():"+rand.nextGaussian());
        //生成一个处于int整数取值范围的伪随机数整数
        System.out.println("rand.nextInt()"+rand.nextInt());
        //生成0~26之间的伪随机整数
        System.out.println("rand.nextInt(26):"+rand.nextInt(26));
        //生成一个处于int整数取值范围的伪随机数整数
        System.out.println("rand.nextLong():"+rand.nextLong());
    }

}

输出如下

猜你喜欢

转载自www.cnblogs.com/yumiaoxia/p/9022263.html