java随机数的有趣用法

直接用代码说明,比较容易理解

package com.wz.other;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
* random的有趣功能
*
* @author Administrator
* @create 2018-04-23 8:42
*/
public class UseRandom {

public static void main(String[] args) {
// 简单用法
// 产生0.0和10.0之间的双精度浮点数
double num = Math.random() * 10;
// 产生0和10之间的整数
long num1 = Math.round(Math.random()*10);

// 进阶用法(每次都要创建Random对象)
Random random = new Random();
int num2 = random.nextInt(10);

// 并发场景(jdk1.7),两个优点,单一实例静态访问,像Math.random()一样灵活
int num3 = ThreadLocalRandom.current().nextInt(10);

// 经验分享
Math.round(Math.random() * 10); // 会使分布不平衡,四舍五入的影响
Math.floor(Math.random() * 11); // 可以解决上面的那个问题

// 在实战项目中,不要使用下面的第一种方法来取整数,而是使用第二种方法
Random rnd = new Random();
// 第一种方法
System.out.println(Math.abs(rnd.nextInt()) % 10);
// 第二种方法
System.out.println(rnd.nextInt(10));

}
}

猜你喜欢

转载自www.cnblogs.com/wadmwz/p/8916151.html