当前位置:网站首页>Four methods of random number generation | random | math | threadlocalrandom | securityrandom
Four methods of random number generation | random | math | threadlocalrandom | securityrandom
2022-07-05 19:50:00 【Bulst】
List of articles
Random
Random Generate random number , There's a constructor , Delivered long Type value , When using empty constructs , In fact, what is conveyed is System.nanoTime() , That is, the value of milliseconds of the current time .
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
public Random(long seed) {
if (getClass() == Random.class)
this.seed = new AtomicLong(initialScramble(seed));
else {
// subclass might have overriden setSeed
this.seed = new AtomicLong();
setSeed(seed);
}
}
Parameters are also called seeds . Generally, it is enough to use null parameter construction , If you specify the value of the seed , Then the generated random numbers are the same , So seeds cannot be written dead .
Java.util.Random The random algorithm implemented in class is pseudorandom , That is to say, random with rules , Is to give seed Randomly generated numbers in the interval of .
Of the same number of seeds Random object , The random numbers generated are exactly the same .
Random It's thread safe , Inside Seed Global variable , When multiple threads generate random numbers , Used cas .
private final AtomicLong seed;
Math.random()
More commonly used methods of generating random numbers , Default 0.0-1.0 Decimal between 【 Left closed right away 】
Its bottom layer calls Random Is a parameter - free construction method , And it cannot be set seed value .
// The underlying call Random Parameter free constructor
double mathRandom = Math.random();
System.out.println(mathRandom);
public static double random() {
return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}
private static final class RandomNumberGeneratorHolder {
static final Random randomNumberGenerator = new Random();
}
ThreadLocalRandom
ThreadLocalRandom yes Java7 Newly added , For concurrent use of multiple threads , Velocity ratio Random Be quick .
ThreadLocalRandom It's through ThreadLocal Improved tool class for random generation , Each thread holds a separate , There is no competition
ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
int threadLocalRandomValue = threadLocalRandom.nextInt(10);
System.out.println(threadLocalRandomValue);
The construction method is private , It can only be in singleton mode , Cannot set seed.
SecurityRandom
SeurityRandom Built in two random number algorithms ,NativePrRNG and SHA1PRNG . adopt new To create , By default NavivePRNG The algorithm generates random numbers , It can also be modified through parameters .
It can also be done through getInstance To initialize the object , Just have a parameter passing algorithm name , The second parameter specifies the algorithm package ,SHA1PRNG Performance ratio of NATIVEPRNG Double the performance , You can set seed , If seed Fix , Then the random result will remain the same .
SecureRandom instance = SecureRandom.getInstanceStrong();
// SecureRandom instance = new SecureRandom();
int instanceValue = instance.nextInt(10);
System.out.println(instanceValue);
SecureRandom instance = SecureRandom.getInstance("SHA1PRNG");
// Set seed value , The result remains unchanged.
instance.setSeed(1);
int instanceValue = instance.nextInt(10);
System.out.println(instanceValue);
JvmRandom
It is essentially the same as Math.random() equally , It's also true Random A kind of , Realize in commons-lang It's a bag .
JVMRandom jvmRandom = new JVMRandom();
int i = jvmRandom.nextInt(10);
System.out.println(i);
public int nextInt(int n) {
return SHARED_RANDOM.nextInt(n);
}
private static final Random SHARED_RANDOM = new Random();
边栏推荐
- 大厂面试必备技能,2022Android不死我不倒
- id选择器和类选择器的区别
- 【obs】QString的UTF-8中文转换到blog打印 UTF-8 char*
- 全网最全的低代码/无代码平台盘点:简道云、伙伴云、明道云、轻流、速融云、集简云、Treelab、钉钉·宜搭、腾讯云·微搭、智能云·爱速搭、百数云
- 【obs】libobs-winrt :CreateDispatcherQueueController
- How to choose the notion productivity tools? Comparison and evaluation of notion, flowus and WOLAI
- 通配符选择器
- Interviewer: what is the internal implementation of set data types in redis?
- 微波雷达感应模块技术,实时智能检测人体存在,静止微小动静感知
- C application interface development foundation - form control (5) - grouping control
猜你喜欢

third-party dynamic library (libcudnn.so) that Paddle depends on is not configured correctl

使用 RepositoryProvider简化父子组件的传值

Password reset of MariaDB root user and ordinary user

Hiengine: comparable to the local cloud native memory database engine

IBM大面积辞退40岁+的员工,掌握这十个搜索技巧让你的工作效率至上提高十倍

通过POI追加数据到excel中小案例

CADD课程学习(7)-- 模拟靶点和小分子相互作用 (半柔性对接 AutoDock)

使用easyexcel模板导出的两个坑(Map空数据列错乱和不支持嵌套对象)

Millimeter wave radar human body sensor, intelligent perception of static presence, human presence detection application
Successful entry into Baidu, 35K monthly salary, 2022 Android development interview answer
随机推荐
PHP利用ueditor实现上传图片添加水印
浅浅的谈一下ThreadLocalInsecureRandom
Microwave radar induction module technology, real-time intelligent detection of human existence, static micro motion and static perception
CADD课程学习(7)-- 模拟靶点和小分子相互作用 (半柔性对接 AutoDock)
IBM大面积辞退40岁+的员工,掌握这十个搜索技巧让你的工作效率至上提高十倍
众昂矿业:2022年全球萤石行业市场供给现状分析
司空见惯 - 英雄扫雷鼠
手机股票开户安全吗?靠不靠谱啊?
Debezium series: record the messages parsed by debezium and the solutions after the MariaDB database deletes multiple temporary tables
Summer Challenge database Xueba notes, quick review of exams / interviews~
Necessary skills for interview in large factories, 2022android will not die, I will not fall
挖财钱堂教育靠谱安全吗?
使用 RepositoryProvider简化父子组件的传值
UWB ultra wideband positioning technology, real-time centimeter level high-precision positioning application, ultra wideband transmission technology
How about testing outsourcing companies?
软件测试是干什么的?学习有啥要求?
Webuploader file upload drag upload progress monitoring type control upload result monitoring control
Multi branch structure
Bitcoinwin (BCW)受邀参加Hanoi Traders Fair 2022
Thread pool parameters and reasonable settings