【问题标题】:ThreadLocalRandom setSeedThreadLocalRandom setSeed
【发布时间】:2017-02-11 11:54:45
【问题描述】:

是否可以向ThreadLocalRandom 提供种子?

looks like it isn't

/**
 * Throws {@code UnsupportedOperationException}.  Setting seeds in
 * this generator is not supported.
 *
 * @throws UnsupportedOperationException always
 */
public void setSeed(long seed) {
    if (initialized)
        throw new UnsupportedOperationException();
    rnd = (seed ^ multiplier) & mask;
}

那么我们可以通过种子使用ThreadLocalRandom,或者它不是为此而设计的吗?

【问题讨论】:

  • 当公共规范已经给你答案时,为什么还要看实现呢? Like the global {@link java.util.Random} generator used by the {@link java.lang.Math} class, a {@code ThreadLocalRandom} is initialized with an internally generated seed that may not otherwise be modified.
  • 是的,你是对的。应该更仔细地阅读它。

标签: java random random-seed


【解决方案1】:

正如@Marko Topolnik 评论的那样,ThreadLocalRandom 不允许设置自己的种子。 您可以使用ThreadLocal<Random> 绕过此问题,如this question 中所述。

【讨论】:

  • 这应该是一条评论。
  • @wscourge 好的,谢谢,我没有足够的声誉发表评论,但我有同样的问题,发现该链接对我来说很有用。
  • @wscourge 不,它应该是一个有用的答案。
猜你喜欢
  • 1970-01-01
  • 2014-06-17
  • 2015-03-08
  • 2020-02-07
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 2018-11-20
  • 1970-01-01
相关资源
最近更新 更多