当前位置: 首页 > news >正文

Java中java.util.Random的用法

java.util.Random是Java中用于生成伪随机数的类,提供了多种生成不同类型随机数的方法。

基本用法

1. 创建Random对象

import java.util.Random;// 创建Random对象(使用默认种子,通常是系统时间)
Random random = new Random();// 创建Random对象(使用指定种子)
Random randomWithSeed = new Random(12345L);

2. 生成不同类型的随机数

Random random = new Random();// 生成整数
int randomInt = random.nextInt();           // 任意整数
int randomIntInRange = random.nextInt(100); // 0-99之间的整数// 生成长整数
long randomLong = random.nextLong();// 生成浮点数
float randomFloat = random.nextFloat();     // 0.0-1.0之间的浮点数
double randomDouble = random.nextDouble();  // 0.0-1.0之间的双精度浮点数// 生成布尔值
boolean randomBoolean = random.nextBoolean();// 生成字节数组
byte[] bytes = new byte[10];
random.nextBytes(bytes);  // 用随机字节填充数组

实际应用示例

1. 生成指定范围的随机数

Random random = new Random();// 生成1-100之间的随机整数
int num1To100 = random.nextInt(100) + 1;// 生成50-100之间的随机整数
int num50To100 = random.nextInt(51) + 50;// 生成-10到10之间的随机整数
int numNegativeToPositive = random.nextInt(21) - 10;

2. 模拟掷骰子

public class DiceRoller {public static void main(String[] args) {Random random = new Random();// 模拟掷一个六面骰子int diceRoll = random.nextInt(6) + 1;System.out.println("骰子点数: " + diceRoll);// 模拟掷两个骰子int dice1 = random.nextInt(6) + 1;int dice2 = random.nextInt(6) + 1;int total = dice1 + dice2;System.out.println("骰子1: " + dice1 + ", 骰子2: " + dice2 + ", 总和: " + total);}
}

3. 随机选择数组元素

public class RandomArrayElement {public static void main(String[] args) {String[] fruits = {"苹果", "香蕉", "橙子", "葡萄", "草莓"};Random random = new Random();// 随机选择一个水果int randomIndex = random.nextInt(fruits.length);String randomFruit = fruits[randomIndex];System.out.println("随机选择的水果: " + randomFruit);// 随机打乱数组顺序for (int i = fruits.length - 1; i > 0; i--) {int j = random.nextInt(i + 1);// 交换元素String temp = fruits[i];fruits[i] = fruits[j];fruits[j] = temp;}System.out.println("打乱后的数组: " + Arrays.toString(fruits));}
}

4. 生成随机密码

public class PasswordGenerator {private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%";public static String generatePassword(int length) {Random random = new Random();StringBuilder password = new StringBuilder();for (int i = 0; i < length; i++) {int randomIndex = random.nextInt(CHARACTERS.length());password.append(CHARACTERS.charAt(randomIndex));}return password.toString();}public static void main(String[] args) {String password = generatePassword(12);System.out.println("生成的密码: " + password);}
}

种子(Seed)的重要性

public class SeedExample {public static void main(String[] args) {// 使用相同种子的Random对象会生成相同的随机数序列Random random1 = new Random(12345L);Random random2 = new Random(12345L);System.out.println("相同种子的随机数序列:");for (int i = 0; i < 5; i++) {System.out.println("random1: " + random1.nextInt(100) + ", random2: " + random2.nextInt(100));}// 使用不同种子的Random对象会生成不同的随机数序列Random random3 = new Random();Random random4 = new Random();System.out.println("\n不同种子的随机数序列:");for (int i = 0; i < 5; i++) {System.out.println("random3: " + random3.nextInt(100) + ", random4: " + random4.nextInt(100));}}
}

线程安全版本

对于多线程环境,可以使用ThreadLocalRandom

import java.util.concurrent.ThreadLocalRandom;public class ThreadLocalRandomExample {public static void main(String[] args) {// 在单个线程中使用int randomNum = ThreadLocalRandom.current().nextInt(1, 101); // 1-100// 在多线程环境中使用Runnable task = () -> {int threadRandom = ThreadLocalRandom.current().nextInt(1000);System.out.println(Thread.currentThread().getName() + ": " + threadRandom);};// 启动多个线程for (int i = 0; i < 5; i++) {new Thread(task).start();}}
}

注意事项

  1. 性能考虑: 创建Random对象相对昂贵,避免在循环中重复创建
  2. 种子安全性: 不要使用容易被猜测的种子
  3. 加密安全: 对于加密应用,使用java.security.SecureRandom
  4. 线程安全: Random是线程安全的,但ThreadLocalRandom在多线程环境中性能更好

这些示例展示了java.util.Random的基本用法和常见应用场景,你可以根据具体需求进行调整和扩展。

http://www.hskmm.com/?act=detail&tid=34377

相关文章:

  • 2025年磨粉机厂家推荐排行榜,雷蒙磨粉机,环辊磨粉机,摆式磨粉机,矿石磨粉机,超微磨粉机,高压磨粉机公司推荐!
  • 我的学习开始及历程
  • 2025信息流代运营推荐:线尚网络精准投放,效果显著!
  • 零售行业绩效流程推行难点及 Tita 目标绩效一体化管理方案
  • Godot-C#处理节点关系
  • 软件工程-结队项目
  • 2025 年防撞钢护栏厂家推荐聊城市泰锌金属材料有限公司,桥梁,不锈钢,复合管,景观,灯光,热镀锌,河道,铝合金,绳索防撞钢护栏公司推荐
  • 2025年聚氨酯制品厂家推荐排行榜,浇注型聚氨酯,聚氨酯预聚体,聚氨酯胶黏剂,聚氨酯组合料,液体聚氨酯,专业品质与创新技术之选
  • Vue中keep-alive实现原理解析
  • 深入学习Spring Boot框架
  • 《探索C语言中数组的奥秘(下)》 - 教程
  • Java异步编程难题拆解
  • 2025年智能防爆灯/工矿灯厂家推荐排行榜,专业安全与高效照明解决方案!
  • 预测不可预测之物的校准学习技术
  • 2025年水产养殖设备厂家推荐排行榜,PP鱼池/微滤机/不锈钢微滤机/锦鲤池微滤机一体机/全自动污水过滤器/生物过滤器/循环水养殖系统公司推荐!
  • Java 无锁方式实现高性能线程
  • java语言程序设计类与对象课后作业 - 20243867孙堃2405
  • 详细介绍:2020年美国新冠肺炎疫情数据分析与可视化
  • java流程控制。
  • Java基础——包机制,JavaDoc生成文档
  • Misaka2298 的写题自检表
  • Java 中 NullPointerException 的 3 个常见原因及解决
  • Java 方法参数传递:到底是值传递还是引用传递?
  • ES6 箭头函数
  • mysql嵌套查询如何利用索引?
  • 解码Linux文件IO之LCD屏原理及应用
  • centos 7.9快速部署ARL(Asset Reconnaissance Lighthouse)资产侦察灯塔系统用于信息收集
  • 3 分钟搞懂 Java 中 this 关键字的用法
  • 折腾笔记[32]-windows部署vscode-server及使用命令行编译c#.net工程
  • Java 中 ArrayList 和 LinkedList 的选择技巧