我是否应该选择ThreadLocalRandom而不是ThreadLocal< Random&gt ;? [英] Should I prefer ThreadLocalRandom over ThreadLocal<Random>?

查看:90
本文介绍了我是否应该选择ThreadLocalRandom而不是ThreadLocal< Random&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在多个线程中使用(种子)Random对象,并且javadocs将我指向

I'm looking to use (seeded) Random objects across multiple threads, and the javadocs pointed me to ThreadLocalRandom which looks great except I can't set the seed, so I can't ensure consistency among different threads or runs. Is there any practical reason to use ThreadLocalRandom or would it be acceptable to do something like the following:

// Pass returned ThreadLocal object to all threads which need it
public static ThreadLocal<Random> threadRandom(final long seed) {
    return new ThreadLocal<Random>(){
        @Override
        protected Random initialValue() {
            return new Random(seed);
        }
    };
}

推荐答案

您可以简单地使用Random,只需确保仅在单个线程中访问每个Random对象即可.

You can simply use Random, just make sure each Random object is only accessed within a single thread.

Random是类似于Vector的古老类,因此不必要地高度同步.他们可能想炫耀Java的线程支持,因为那时这很重要.同样,Java主要是打算在大多数具有单个处理器的消费类PC上运行,因此同步不会像今天在多处理器上那样影响扩展性.

Random, being an ancient class like Vector, is unnecessarily heavily synchronized. They probably wanted to show off Java's threading support since it was a big deal at that time. Also Java was mostly intended to run on consumer PCs which mostly had a single processor so synchronization didn't impact scaling like it does today on multiprocessors.

现在一个明显的答案是提供Random的线程不安全版本,就像提供ArrayList的线程不安全替代Vector一样.那没有发生,相反,我们得到了ThreadLocalRandom.这有点奇怪,不确定其背后的动机是什么.在java8中,进一步优化了ThreadLocalRandom以直接在Thread对象中的某些int字段上进行操作.

Now an obvious answer is to provide a thread-unsafe version of Random, just like providing the thread-unsfae ArrayList as the alternative to Vector. That didn't happen, instead, we got ThreadLocalRandom. That is kind of odd, not sure what's the motivation behind that. In java8, ThreadLocalRandom is further optimized to operate directly on some int fields in the Thread object.

这篇关于我是否应该选择ThreadLocalRandom而不是ThreadLocal&lt; Random&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆