Skip to content

Instantly share code, notes, and snippets.

@yongboy
Created February 2, 2012 07:35
Show Gist options
  • Save yongboy/1722196 to your computer and use it in GitHub Desktop.
Save yongboy/1722196 to your computer and use it in GitHub Desktop.
ThreadLocalRandom简单测试
package com.learn.jsry166y.demo.random;
import java.util.ArrayList;
import java.util.List;
import jsr166y.Phaser;
import jsr166y.ThreadLocalRandom;
import junit.framework.Assert;
import org.junit.Test;
/**
* ThreadLocalRandom简单测试
* @author yongboy
* @time 2012-2-2
* @version 1.0
*/
public class RandomTest {
@Test
public void testSpeed() {
final int MAX = 100000;
ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
long start = System.nanoTime();
for (int i = 0; i < MAX; i++) {
threadLocalRandom.nextDouble();
}
long end = System.nanoTime() - start;
System.out.println("use time1 : " + end);
long start2 = System.nanoTime();
for (int i = 0; i < MAX; i++) {
Math.random();
}
long end2 = System.nanoTime() - start2;
System.out.println("use time2 : " + end2);
Assert.assertTrue(end2 > end);
}
// 判断两个线程之间所引用的ThreadLocalRandom实例是不一样的
@Test
public void testInstance() {
final ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
final List<ThreadLocalRandom> randomList = new ArrayList<ThreadLocalRandom>();
// CountDownLatch的用法
final Phaser barrier = new Phaser(1);
new Thread() {
@Override
public void run() {
randomList.add(ThreadLocalRandom.current());
barrier.arrive();
}
}.start();
barrier.awaitAdvance(barrier.getPhase());
if (randomList.isEmpty()) {
throw new NullPointerException();
}
Assert.assertTrue(threadLocalRandom != randomList.get(0));
}
@Test
public void testHowtoUse(){
final ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
final int MAX = 100;
int result = threadLocalRandom.nextInt(0, 100);
Assert.assertTrue(MAX > result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment