Ai
2 Star 3 Fork 1

汪少棠/java-se

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
RandomTest.java 2.59 KB
一键复制 编辑 原始数据 按行查看 历史
汪少棠 提交于 2021-12-31 19:55 +08:00 . Java SE 随机数生成器 Random
package org.example.uitls;
import org.junit.Test;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* Java SE 随机数生成器 Random
*
* @author wangMaoXiong
* @version 1.0
* @date 2021/12/31 18:50
*/
public class RandomTest {
/**
* 实际项目中不推荐使用 Random、建议使用 ThreadLocalRandom、SecureRandom
* int nextInt():返回此随机数生成器序列中的下一个伪随机,包括负数,如 -8022357372481675815
* long nextLong():返回此随机数生成器序列中的下一个伪随机,包括负数,如 -686133030
* int nextInt(int bound):返回 [0,bound) 之间的随机数
* boolean nextBoolean():随机返回 true 或者 false.
* double nextDouble(): 返回 (0,1) 之间的随机浮点型,如 0.22474496933706056
* float nextFloat():返回 (0,1) 之间的随机浮点型,如 0.9701549
*/
@Test
public void testRandom() {
System.out.println(new Random().nextInt());
System.out.println(new Random().nextInt(1000));
System.out.println(new Random().nextBoolean());
System.out.println(new Random().nextDouble());
System.out.println(new Random().nextFloat());
System.out.println(new Random().nextLong());
}
/**
* Java jdk 1.7 开始在 concurrent 包内添加了 ThreadLocalRandom 类,与当前线程隔离的随机数生成器。
* ThreadLocalRandom 不是加密安全的,在安全敏感的应用程序中考虑使用 SecureRandom。
*/
@Test
public void testSecureRandom2() {
System.out.println(ThreadLocalRandom.current().nextInt());
System.out.println(ThreadLocalRandom.current().nextInt(1000));
System.out.println(ThreadLocalRandom.current().nextBoolean());
System.out.println(ThreadLocalRandom.current().nextDouble());
System.out.println(ThreadLocalRandom.current().nextFloat());
System.out.println(ThreadLocalRandom.current().nextLong());
}
/**
* SecureRandom 提供了一个密码强的随机数生成器,调用者通过无参数构造函数或 getInstance 方法之一获取一个 SecureRandom 实例。
*/
@Test
public void testSecureRandom() {
System.out.println(new SecureRandom().nextInt());
System.out.println(new SecureRandom().nextInt(1000));
System.out.println(new SecureRandom().nextBoolean());
System.out.println(new SecureRandom().nextDouble());
System.out.println(new SecureRandom().nextFloat());
System.out.println(new SecureRandom().nextLong());
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/wangmx1993/java-se.git
git@gitee.com:wangmx1993/java-se.git
wangmx1993
java-se
java-se
master

搜索帮助