并发生成器
java中有两种并发生成器:
- 安全型随机数生成:根据机器的本身特性,生成随机数,效率较低;
- 伪随机数生成器:根据seed生成随机数,但是效率较高;
并发中的伪随机数生成器
在Java中,我们通常使用的随机数生成器是Random
。
Java7中发布了新的ThreadLocalRandom
。
实验
8线程,每个线程,循环1000000次,两者效率差15倍左右:
Random
:花费3300ms左右ThreadLocalRandom
:花费200ms左右
具体的代码:
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();
}
}
}