Java开发笔记(一百五十五)生成随机数的几种途径
<p>随机数生成是一个常见的业务场景,比如摇号、抽奖等等都需要随机数。Java代码主要有三种随机数的生成方式,包括Math.random、Random、ThreadLocalRandom等,分别说明如下:</p><p><span style="font-size: 18pt"><strong>1、Math.random</strong></span></p>
<p>Java代码调用Math.random()会返回一个大于等于0.0且小于1.0的双精度类型随机数,即取值区间落在[0,1)。可见该方式获取的随机数是个小数,如果业务需要随机整数的话,就得把随机小数放大若干倍后再取整,使得Math.random用起来多有不便。</p>
<p><span style="font-size: 18pt"><strong>2、Random</strong></span></p>
<p>查看Math.random的源码,发现该函数实际调用了randomNumberGenerator的nextDouble方法:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">public static double random() {
return RandomNumberGeneratorHolder.randomNumberGenerator.nextDouble();
}
</pre>
</div>
<p> </p>
<p>查找randomNumberGenerator发现该对象为Random类型,且其实例由new Random()获得:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">private static final class RandomNumberGeneratorHolder {
static final Random randomNumberGenerator = new Random();
}
</pre>
</div>
<p> </p>
<p>可见Math.random的随机数来自于Random。除了nextDouble方法,Random还提供了nextFloat、nextInt、nextLong等方法用于生成对应类型的随机数。就生成随机整数而言,还能通过nextInt(**)获取指定范围的随机整数。例如以下代码生成的随机整数取值区间为[0,100):</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">Random random = new Random();
int result = random.nextInt(100);
</pre>
</div>
<p><strong style="font-size: 18pt">3、ThreadLocalRandom</strong></p>
<p>虽然在多数场合Random已经够用了,但在多线程情况下,各线程会竞争同一个随机种子,导致有概率因抢占失败而自旋重试。<br>为了解决Random在多线程场合出现性能降低的问题,Java提供了保证线程安全的ThreadLocalRandom。在多线程情况下,ThreadLocalRandom会给每个线程维护单独的随机种子,这样各线程各自使用自己的随机种子,就避免了抢占失败的问题了。<br>ThreadLocalRandom的用法很简单,仅需以下两行代码即可获得取值区间为[0,100)的随机整数:</p>
<div class="cnblogs_Highlighter">
<pre class="brush:csharp;gutter:true;">ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
threadLocalRandom.nextInt(100);
</pre>
</div>
<p> </p>
<p>更多Java技术文章参见《Java开发笔记(序)章节目录》</p><br><br>
来源:https://www.cnblogs.com/pinlantu/p/18977068
頁:
[1]