尧图网站建设 尧图网络
  • 首页
  • 关于我们
  • 服务项目
  • 案例展示
  • 建站流程
  • 资讯中心
  • 联系我们
首页/资讯中心/详情

Java中java.util.Random的用法

Java中java.util.Random的用法
📅 发布时间:2026/6/19 18:19:09

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的基本用法和常见应用场景,你可以根据具体需求进行调整和扩展。

相关新闻

  • 从汇编角度看C++优化:编译器真正做了什么 - 教程
  • 实用指南:【从零开始学习RabbitMQ】
  • Godot-C#处理节点关系

最新新闻

  • 上海汽车音响改装选哪家?上海音乐人生,二十年赛事级连锁标杆门店 - 音乐人生汽车音响
  • 技术解析:从Tri-Plane到3D GAN,如何实现高效且一致的神经渲染
  • 通过Selenium实现网页截图来生成应用封面
  • 2026苏州钻石回收实测|国标4C定级,全城无套路靠谱门店变现指南 - 薛定谔的梨花猫
  • C语言宽字符处理:wmemcmp、wmemcpy、wprintf核心函数详解与实战
  • 多模态大语言模型LISA

日新闻

  • 5分钟掌握Python进化算法:Geatpy高性能优化工具完全指南
  • Microchip 24AA044 EEPROM选型与应用全指南:从参数解析到实战编程
  • 华为的鸿蒙到底有多牛?为什么称作遥遥领先?

周新闻

  • 3步解锁iOS设备:applera1n激活锁绕过完全指南
  • 39 2026 人工智能证书终极盘点,普通人选 AI 证书可以从这些方向入手
  • Redis 暴露公网有多危险?从端口检查到补救步骤

月新闻

  • 【总结】入门篇:50句话让你记住架构核心概念
  • WeChatMsg技术方案解析:实现Mac微信数据自主管理的完整解决方案
  • WeChatMsg:革新性微信数据备份方案,打造你的专属数字记忆库

关于尧图

  • 公司简介
  • 团队介绍
  • 企业文化
  • 荣誉资质

服务项目

  • 定制开发
  • 电商建站
  • UI 设计
  • 运维服务

快速链接

  • 案例展示
  • 建站流程
  • 常见问题
  • 资讯中心

联系方式

  • 📍北京市朝阳区互联网产业园 A 座 10 层
  • 📞400-888-8888
  • ✉️contact@rkmt.cn
  • 🕐周一至周日 9:00-21:00

© 2024 北京尧图网络科技有限公司 版权所有 | 京 ICP 备 XXXXXXXX 号