併發生成器
java中有兩種併發生成器:java
- 安全型隨機數生成:根據機器的自己特性,生成隨機數,效率較低;
- 僞隨機數生成器:根據seed生成隨機數,可是效率較高;
併發中的僞隨機數生成器
在Java中,咱們一般使用的隨機數生成器是Random
。安全
Java7中發佈了新的ThreadLocalRandom
。併發
實驗
8線程,每一個線程,循環1000000次,二者效率差15倍左右:dom
Random
:花費3300ms左右ThreadLocalRandom
:花費200ms左右
具體的代碼:ide
import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ThreadLocalRandom; /** * 簡潔版的併發隨機數生成實驗 * * @author Beihai * @date 18/4/11 */ public class SimpleConcurrentRandomTest { public static final Long COUNT= 10000000L; public static final Integer THREAD_COUNT= 8; public static void main(String[] args) { //concurrentRandomTest(); randomTest(); } public static void concurrentRandomTest() { Long start = System.currentTimeMillis(); CountDownLatch downLatch = new CountDownLatch(THREAD_COUNT); Random rdn = new Random(); for(int i=0; i<THREAD_COUNT; i++){ new Thread(new Runnable() { @Override public void run() { int sum = 0; try { downLatch.countDown(); downLatch.await(); for (int i = 0; i < COUNT; i++) { sum += ThreadLocalRandom.current().nextInt(); } System.out.printf("ThreadLocalRandom: 8 threads circulation %d, spend: %d ms\n", COUNT, System.currentTimeMillis()-start); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } public static void randomTest() { Long start = System.currentTimeMillis(); CountDownLatch downLatch = new CountDownLatch(THREAD_COUNT); Random rdn = new Random(100); for(int i=0; i<THREAD_COUNT; i++){ new Thread(new Runnable() { @Override public void run() { int sum = 0; try { downLatch.countDown(); downLatch.await(); for (int i = 0; i < COUNT; i++) { sum += rdn.nextInt(); } System.out.printf("Random: 8 threads circulation %d, spend: %d ms\n", COUNT, System.currentTimeMillis()-start); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } } }