Java併發中的隨機數生成

併發生成器

java中有兩種併發生成器:java

  1. 安全型隨機數生成:根據機器的自己特性,生成隨機數,效率較低;
  2. 僞隨機數生成器:根據seed生成隨機數,可是效率較高;

併發中的僞隨機數生成器

在Java中,咱們一般使用的隨機數生成器是Random安全

Java7中發佈了新的ThreadLocalRandom併發

實驗

8線程,每一個線程,循環1000000次,二者效率差15倍左右:dom

  1. Random:花費3300ms左右
  2. 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();
        }
    }
}
相關文章
相關標籤/搜索