java中ThreadLocalRandom的使用詳解
在java中我們通常會(huì)需要使用到j(luò)ava.util.Random來便利的生產(chǎn)隨機(jī)數(shù)。但是Random是線程安全的,如果要在線程環(huán)境中的話就有可能產(chǎn)生性能瓶頸。
我們以Random中常用的nextInt方法為例來具體看一下:
public int nextInt() { return next(32); }
nextInt方法實(shí)際上調(diào)用了下面的方法:
protected int next(int bits) { long oldseed, nextseed; AtomicLong seed = this.seed; do { oldseed = seed.get(); nextseed = (oldseed * multiplier + addend) & mask; } while (!seed.compareAndSet(oldseed, nextseed)); return (int)(nextseed >>> (48 - bits)); }
從代碼中我們可以看到,方法內(nèi)部使用了AtomicLong,并調(diào)用了它的compareAndSet方法來保證線程安全性。所以這個(gè)是一個(gè)線程安全的方法。
其實(shí)在多個(gè)線程環(huán)境中,Random根本就需要共享實(shí)例,那么該怎么處理呢?
在JDK 7 中引入了一個(gè)ThreadLocalRandom的類。ThreadLocal大家都知道就是線程的本地變量,而ThreadLocalRandom就是線程本地的Random。
我們看下怎么調(diào)用:
ThreadLocalRandom.current().nextInt();
我們來為這兩個(gè)類分別寫一個(gè)benchMark測(cè)試:
public class RandomUsage { public void testRandom() throws InterruptedException { ExecutorService executorService=Executors.newFixedThreadPool(2); Random random = new Random(); List<Callable<Integer>> callables = new ArrayList<>(); for (int i = 0; i < 1000; i++) { callables.add(() -> {return random.nextInt(); }); } executorService.invokeAll(callables); } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder().include(RandomUsage.class.getSimpleName())// 預(yù)熱5輪.warmupIterations(5)// 度量10輪.measurementIterations(10).forks(1).build(); new Runner(opt).run(); }}public class ThreadLocalRandomUsage { @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MICROSECONDS) public void testThreadLocalRandom() throws InterruptedException { ExecutorService executorService=Executors.newFixedThreadPool(2); List<Callable<Integer>> callables = new ArrayList<>(); for (int i = 0; i < 1000; i++) { callables.add(() -> {return ThreadLocalRandom.current().nextInt(); }); } executorService.invokeAll(callables); } public static void main(String[] args) throws RunnerException { Options opt = new OptionsBuilder().include(ThreadLocalRandomUsage.class.getSimpleName())// 預(yù)熱5輪.warmupIterations(5)// 度量10輪.measurementIterations(10).forks(1).build(); new Runner(opt).run(); }}
分析運(yùn)行結(jié)果,我們可以看出ThreadLocalRandom在多線程環(huán)境中會(huì)比Random要快。
本文的例子可以參考https://github.com/ddean2009/learn-java-concurrency/tree/master/ThreadLocalRandom
到此這篇關(guān)于java中ThreadLocalRandom的使用詳解的文章就介紹到這了,更多相關(guān)java ThreadLocalRandom內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. moment轉(zhuǎn)化時(shí)間戳出現(xiàn)Invalid Date的問題及解決2. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊3. Java剖析工具YourKit 發(fā)布5.0版本4. 開發(fā)效率翻倍的Web API使用技巧5. python實(shí)現(xiàn)坦克大戰(zhàn)6. 使用JSP技術(shù)實(shí)現(xiàn)一個(gè)簡(jiǎn)單的在線測(cè)試系統(tǒng)的實(shí)例詳解7. 跟我學(xué)XSL(一)第1/5頁8. Python中內(nèi)建模塊collections如何使用9. 為什么你的android代碼寫得這么亂10. 解決VUE項(xiàng)目localhost端口服務(wù)器拒絕連接,只能用127.0.0.1的問題
