当前位置:网站首页>Things like random
Things like random
2022-07-07 00:01:00 【Bulst】
Last article , We explained several ways to generate random numbers .
Next , Let's take a closer look Random How is it realized .
Before the start , Let's make a small demo
public static void main(String[] args) {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int randomValue = random.nextInt(10);
System.out.println(randomValue);
}
}
This procedure , How many times do you run , It generates different numbers .
And you add a seed to it , It generates the same sequence .
such as
public static void main(String[] args) {
Random random = new Random(1);
for (int i = 0; i < 10; i++) {
int randomValue = random.nextInt(10);
System.out.println(randomValue);
}
}
Why is that ?
You must have read the previous article , It's already clear .
because Random Default constructor , Use time as seed , So the values generated each time are different .
/** * Creates a new random number generator. This constructor sets * the seed of the random number generator to a value very likely * to be distinct from any other invocation of this constructor. */
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
Let's take a look at how to generate random numbers .
// bound: The range of random numbers
public int nextInt(int bound) {
if (bound <= 0)
throw new IllegalArgumentException(BadBound);
// track 【 Make new seeds from old ones 】
int r = next(31);
// Calculate the random number according to the new seed
int m = bound - 1;
if ((bound & m) == 0) // i.e., bound is a power of 2
r = (int)((bound * (long)r) >> 31);
else {
for (int u = r;
u - (r = u % bound) + m < 0;
u = next(31))
;
}
In the case of a single thread, each call nextInt New seeds are calculated from old seeds , This can guarantee the randomness of random numbers .
But in multithreading, multiple threads may take the same old seed to calculate the new seed , This will cause multiple threads to produce the same new seeds , Because the algorithm of generating random numbers is fixed , Therefore, it will cause multiple threads to produce the same random value .
therefore int r = next(31);
To be atomic , That is, when multiple threads calculate a new seed based on the same old seed , After the new seed of the first thread is calculated , The second thread discards its old seeds , Use the new seed of the first thread to calculate your new seed , By analogy , Only this is guaranteed , To ensure that the random number generated by multithreading is random .
track 【 Make new seeds from old ones 】
protected int next(int bits) {
long oldseed, nextseed;
// Atomic classes
AtomicLong seed = this.seed;
do {
oldseed = seed.get();
nextseed = (oldseed * multiplier + addend) & mask;
} while (!seed.compareAndSet(oldseed, nextseed));
return (int)(nextseed >>> (48 - bits));
}
ah , this …
Typical CAS Well .
Forget it , Eating out , Wait for the next one , Let's have a good talk CAS.
边栏推荐
- The best sister won the big factory offer of 8 test posts at one go, which made me very proud
- 陀螺仪的工作原理
- 零代码高回报,如何用40套模板,能满足工作中95%的报表需求
- Do you still have to rely on Simba to shout for a new business that is Kwai?
- 基于jsp+servlet+mysql框架的旅游管理系统【源码+数据库+报告】
- 【212】php发送post请求有哪三种方法
- 从外企离开,我才知道什么叫尊重跟合规…
- Hydrogen future industry accelerates | the registration channel of 2022 hydrogen energy specialty special new entrepreneurship competition is opened!
- DAY FOUR
- Pdf document signature Guide
猜你喜欢
[OFDM communication] OFDM system signal detection based on deep learning with matlab code
Design a red envelope grabbing system
基于jsp+servlet+mysql框架的旅游管理系统【源码+数据库+报告】
MATLIB从excel表中读取数据并画出函数图像
GEO数据挖掘(三)使用DAVID数据库进行GO、KEGG富集分析
什么是响应式对象?响应式对象的创建过程?
matplotlib画柱状图并添加数值到图中
DAY THREE
The largest single investment in the history of Dachen was IPO today
[unmanned aerial vehicle] multi unmanned cooperative task allocation program platform, including Matlab code
随机推荐
ldap创建公司组织、人员
DAY TWO
matplotlib画柱状图并添加数值到图中
Gradle knowledge generalization
Do you still have to rely on Simba to shout for a new business that is Kwai?
PostgreSQL高可用之repmgr(1主2从+1witness)+Pgpool-II实现主从切换+读写分离
rancher集成ldap,实现统一账号登录
PostgreSQL uses pgpool II to realize read-write separation + load balancing
STM32 enters and wakes up the stop mode through the serial port
自动化测试工具Katalon(Web)测试操作说明
How rider uses nuget package offline
Use Yum or up2date to install the postgresql13.3 database
Oracle对表进行的常用修改命令
Gold three silver four, don't change jobs
How to use vector_ How to use vector pointer
专为决策树打造,新加坡国立大学&清华大学联合提出快速安全的联邦学习新系统
Typescript incremental compilation
[CVPR 2022] target detection sota:dino: Detr with improved detecting anchor boxes for end to end object detection
Huawei mate8 battery price_ Huawei mate8 charges very slowly after replacing the battery
数据运营平台-数据采集[通俗易懂]