这是一个线程本地变量,每个生成随机数的线程都有一个不同的生成器,但是都在同一个类中被管理。
current()方法:这是一个静态方法,返回与当前线程关联的TaskLocalRandom对象,所以可以使用这个对象生成随机数
public static ThreadLocalRandom current() {
if (((), PROBE) == 0)
localInit();
return instance;
}
package concurrencycollection;
import ;
public class TaskLocalRandom implements Runnable {
public TaskLocalRandom() {
// TODO Auto-generated constructor stub
();
}
@Override
public void run() {
// TODO Auto-generated method stub
String name = ().getName();
for (int i = 0; i < 10; i++) {
("%s : %s\n", name, ()
.nextInt(100));
}
}
}
package concurrencycollection;
public class Main {
public void testTaskLocalRandom() {
Thread[] threads = new Thread[3];
for (int i = 0; i < 3; i++) {
TaskLocalRandom taskLocalRandom = new TaskLocalRandom();
threads[i] = new Thread(taskLocalRandom);
threads[i].start();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Main().testTaskLocalRandom();
}
}