添加 随机数生成

This commit is contained in:
2026-08-05 06:45:56 +08:00
parent 350f59bfe2
commit 949030d606
5 changed files with 223 additions and 1 deletions

View File

@@ -119,7 +119,7 @@ mvn package
编译成功后,将 `target/gnu-java-utils-library-1.0.0.jar` 放入项目依赖中。</br> 编译成功后,将 `target/gnu-java-utils-library-1.0.0.jar` 放入项目依赖中。</br>
或者在releases中下载最新版jar包放入项目依赖中。 或者在releases中下载最新版jar包放入项目依赖中。
#### 使用示例 #### 使用示例
**pom.xml** **pom.xml**
```xml ```xml

View File

@@ -1,6 +1,7 @@
package top.gtb520.java.gnu.java.utils.library; package top.gtb520.java.gnu.java.utils.library;
import top.gtb520.java.gnu.java.utils.library.utils.print.ColorNameEnum; import top.gtb520.java.gnu.java.utils.library.utils.print.ColorNameEnum;
import top.gtb520.java.gnu.java.utils.library.utils.processing.random.defaults;
public interface main { public interface main {
// 压缩包操作相关接口与方法 // 压缩包操作相关接口与方法
@@ -38,4 +39,11 @@ public interface main {
top.gtb520.java.gnu.java.utils.library.utils.print.echo.ColorHexPrintln(Message, ColorCode); top.gtb520.java.gnu.java.utils.library.utils.print.echo.ColorHexPrintln(Message, ColorCode);
} }
} }
// 随机数生成接口与方法
interface random {
static int defaule(int start_scope, int end_scope) {
return defaults.random(start_scope, end_scope);
}
}
} }

View File

@@ -0,0 +1,25 @@
package top.gtb520.java.gnu.java.utils.library.utils.processing.random;
import java.util.concurrent.ThreadLocalRandom;
public class defaults {
/**
* 根据输入的范围生成随机数
* @param start_scope 起始范围
* @param end_scope 结束范围
* @return 随机数
*/
public static int random(int start_scope, int end_scope) {
int random_double;
// 处理边界,确保起始范围小于等于结束范围
if (start_scope > end_scope) {
System.out.println("起始范围不能大于结束范围");
throw new IllegalArgumentException("起始范围不能大于结束范围");
}
// 生成随机数
random_double = ThreadLocalRandom.current().nextInt(start_scope, end_scope + 1);
return random_double;
}
}

View File

@@ -0,0 +1,47 @@
package top.gtb520.java.gnu.java.utils.library.utils.processing.random;
import top.gtb520.java.gnu.java.utils.library.main;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;
// 毫无意义的随机数测试代码,在循环中执行随机数生成 10 亿次
public class Test {
public static void main(String[] args) {
int totalTasks = 1_000_000_000;
// 根据CPU核心数创建固定大小的线程池避免创建过多线程导致上下文切换开销
int threadCount = Runtime.getRuntime().availableProcessors();
ExecutorService executor = Executors.newFixedThreadPool(threadCount);
// 将总任务量平均分配给每个线程
int tasksPerThread = totalTasks / threadCount;
for (int t = 0; t < threadCount; t++) {
final int start = t * tasksPerThread;
// 处理余数,确保最后一个线程承担剩余任务
final int end = (t == threadCount - 1) ? totalTasks : start + tasksPerThread;
executor.submit(() -> {
// 【核心优化1】使用 ThreadLocalRandom 替代共享 Random
// 每个线程拥有独立的 seed完全无锁避免高并发下的 CAS 竞争
ThreadLocalRandom random = ThreadLocalRandom.current();
// 【核心优化2】将 I/O 与计算分离
// 在实际业务中,应只返回计算结果,而不是在循环中打印
for (int i = start; i < end; i++) {
int random_i = random.nextInt(1, 1000000001); // [1, 1000000000]
// 如果确实需要输出建议降低频率例如每1000万次输出一次
// if (i % 10000 == 0) {
// System.out.println("随机数: " + random_i + " 当前循环位置: " + i);
// }
System.out.println("随机数: " + random_i + " 当前循环位置: " + i);
}
});
}
// 优雅关闭线程池
executor.shutdown();
}
}

View File

@@ -0,0 +1,142 @@
package top.gtb520.java.gnu.java.utils.library.utils.processing.random;
public class defauleTest {
static int passed = 0;
static int failed = 0;
public static void main(String[] args) {
System.out.println("========== defaults.random 测试开始 ==========");
testRandomInRange();
testRandomSameStartAndEnd();
testRandomNegativeRange();
testRandomReversedRange();
testRandomLargeRange();
testRandomDistribution();
System.out.println("========================================");
System.out.println("测试完成: 通过 " + passed + ", 失败 " + failed);
if (failed > 0) {
System.exit(1);
}
}
/**
* 测试正常范围内的随机数
*/
static void testRandomInRange() {
String testName = "testRandomInRange";
try {
for (int i = 0; i < 100; i++) {
int result = defaults.random(1, 10);
if (result < 1 || result > 10) {
assertCondition(testName + " - 随机数应在[1,10]范围内,实际: " + result, false);
return;
}
}
assertCondition(testName + " - 100次随机数均在[1,10]范围内", true);
} catch (Exception e) {
assertCondition(testName + " - 不应抛出异常: " + e.getMessage(), false);
}
}
/**
* 测试起始值等于结束值
*/
static void testRandomSameStartAndEnd() {
String testName = "testRandomSameStartAndEnd";
try {
int result = defaults.random(5, 5);
assertCondition(testName + " - 结果应等于5实际: " + result, result == 5);
} catch (Exception e) {
assertCondition(testName + " - 不应抛出异常: " + e.getMessage(), false);
}
}
/**
* 测试负数范围
*/
static void testRandomNegativeRange() {
String testName = "testRandomNegativeRange";
try {
for (int i = 0; i < 100; i++) {
int result = defaults.random(-10, -1);
if (result < -10 || result > -1) {
assertCondition(testName + " - 随机数应在[-10,-1]范围内,实际: " + result, false);
return;
}
}
assertCondition(testName + " - 100次随机数均在[-10,-1]范围内", true);
} catch (Exception e) {
assertCondition(testName + " - 不应抛出异常: " + e.getMessage(), false);
}
}
/**
* 测试起始值大于结束值应抛出异常
*/
static void testRandomReversedRange() {
String testName = "testRandomReversedRange";
try {
defaults.random(10, 1);
assertCondition(testName + " - 应抛出IllegalArgumentException", false);
} catch (IllegalArgumentException e) {
assertCondition(testName + " - 应抛出IllegalArgumentException", true);
} catch (Exception e) {
assertCondition(testName + " - 异常类型不正确: " + e.getClass().getName(), false);
}
}
/**
* 测试大范围随机数
*/
static void testRandomLargeRange() {
String testName = "testRandomLargeRange";
try {
for (int i = 0; i < 100; i++) {
int result = defaults.random(-1000000, 1000000);
if (result < -1000000 || result > 1000000) {
assertCondition(testName + " - 随机数超出范围,实际: " + result, false);
return;
}
}
assertCondition(testName + " - 100次随机数均在[-1000000,1000000]范围内", true);
} catch (Exception e) {
assertCondition(testName + " - 不应抛出异常: " + e.getMessage(), false);
}
}
/**
* 测试随机数分布(验证不会总是返回同一个值)
*/
static void testRandomDistribution() {
String testName = "testRandomDistribution";
try {
int first = defaults.random(1, 1000000);
boolean hasDifferent = false;
for (int i = 0; i < 100; i++) {
int result = defaults.random(1, 1000000);
if (result != first) {
hasDifferent = true;
break;
}
}
assertCondition(testName + " - 100次调用应产生不同随机数", hasDifferent);
} catch (Exception e) {
assertCondition(testName + " - 不应抛出异常: " + e.getMessage(), false);
}
}
// ========== 辅助方法 ==========
static void assertCondition(String message, boolean condition) {
if (condition) {
System.out.println("[PASS] " + message);
passed++;
} else {
System.out.println("[FAIL] " + message);
failed++;
}
}
}