当前位置:网站首页>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.
边栏推荐
- (LeetCode)两数之和
- 零代码高回报,如何用40套模板,能满足工作中95%的报表需求
- 刘永鑫报告|微生物组数据分析与科学传播(晚7点半)
- 氢创未来 产业加速 | 2022氢能专精特新创业大赛报名通道开启!
- kubernetes部署ldap
- Rider离线使用Nuget包的方法
- DAY ONE
- Basic chart interpretation of "Oriental selection" hot out of circle data
- Hydrogen future industry accelerates | the registration channel of 2022 hydrogen energy specialty special new entrepreneurship competition is opened!
- 编译logisim
猜你喜欢
刘永鑫报告|微生物组数据分析与科学传播(晚7点半)
什么是响应式对象?响应式对象的创建过程?
App general function test cases
The programmer said, "I'm 36 years old, and I don't want to be rolled, let alone cut."
基于SSM框架实现的房屋租赁管理系统
Gradle知識概括
从外企离开,我才知道什么叫尊重跟合规…
Newsletter L Huobi ventures is in-depth contact with genesis public chain
Wind chime card issuing network source code latest version - commercially available
DAY FOUR
随机推荐
Competition between public and private chains in data privacy and throughput
Who said that new consumer brands collapsed? Someone behind me won
DAY SIX
Asset security issues or constraints on the development of the encryption industry, risk control + compliance has become the key to breaking the platform
app通用功能測試用例
Wechat applet UploadFile server, wechat applet wx Uploadfile[easy to understand]
Typescript incremental compilation
数据运营平台-数据采集[通俗易懂]
【向量检索研究系列】产品介绍
PostgreSQL高可用之repmgr(1主2从+1witness)+Pgpool-II实现主从切换+读写分离
rancher集成ldap,实现统一账号登录
A way of writing SQL, update when matching, or insert
vector的使用方法_vector指针如何使用
DAY ONE
How about the order management of okcc call center
使用yum来安装PostgreSQL13.3数据库
Do you still have to rely on Simba to shout for a new business that is Kwai?
Data operation platform - data collection [easy to understand]
MySQL主从之多源复制(3主1从)搭建及同步测试
Quickly use various versions of PostgreSQL database in docker