java.util.concurrent.threadlocalrandom
是从jdk 1.7
开始引入的实用程序类,当需要多个线程或forkjointasks
来生成随机数时很有用。 它提高了性能,并且比math.random()
方法占用更少的资源。
以下是threadlocalrandom
类中可用的重要方法的列表。
编号 | 方法 | 说明 |
---|---|---|
1 | public static threadlocalrandom current() |
返回当前线程的threadlocalrandom 。 |
2 | protected int next(int bits) |
生成下一个伪随机数。 |
3 | public double nextdouble(double n) |
返回伪随机,均匀分布在0(含)和指定值(独占)之间的double 值。 |
4 | public double nextdouble(double least, double bound) |
返回在给定的least 值(包括)和bound (不包括)之间的伪随机均匀分布的值。 |
5 | public int nextint(int least, int bound) |
返回在给定的least 值(包括)和bound (不包括)之间的伪随机均匀分布的整数值。 |
6 | public long nextlong(long n) |
返回伪随机均匀分布的值在0(含)和指定值(不包括)之间的长整数值。 |
7 | public long nextlong(long least, long bound) |
返回在给定的最小值(包括)和bound (不包括)之间的伪随机均匀分布的长整数值。 |
8 | public void setseed(long seed) |
设置伪随机的种子值,抛出unsupportedoperationexception 异常。 |
以下testthread
程序演示了lock
接口的一些方法。 这里我们使用lock()
获取锁和unlock()
来释放锁。
import java.util.random;
import java.util.concurrent.locks.condition;
import java.util.concurrent.locks.lock;
import java.util.concurrent.locks.reentrantlock;
import java.util.concurrent.threadlocalrandom;
public class testthread {
public static void main(final string[] arguments) {
system.out.println("random integer: " + new random().nextint());
system.out.println("seeded random integer: " + new random(15).nextint());
system.out.println("thread local random integer: " + threadlocalrandom.current().nextint());
final threadlocalrandom random = threadlocalrandom.current();
random.setseed(15); //exception will come as seeding is not allowed in threadlocalrandom.
system.out.println( "seeded thread local random integer: " + random.nextint());
}
}
执行上面代码,将产生以下结果 -
random integer: 694316820
seeded random integer: -1159716814
exception in thread "main" thread local random integer: -1324834819
java.lang.unsupportedoperationexception
at java.util.concurrent.threadlocalrandom.setseed(threadlocalrandom.java:236)
at com.h3.testthread.main(testthread.java:18)