您可以将
Random
当前线程执行模拟的实例。由于模拟和线程之间没有1:1的关系,因此应将此关联封装在专用的管理器类中,该类强制初始化和清理线程局部变量,并拒绝无效使用:
public class RandomManager {
private static ThreadLocal<Random> RANDOMS = new ThreadLocal<>();
public static void withRandom(Random rnd, Runnable run) {
Objects.requireNonNull(rnd);
Objects.requireNonNull(run);
if(RANDOMS.get() != null) throw new IllegalStateException("nested invocation");
RANDOMS.set(rnd);
try {
run.run();
}
finally {
RANDOMS.remove();
}
}
// get random integer between min and max (inclusive)
public static int randInt(int min, int max) {
Random r = RANDOMS.get();
if(r == null) throw new IllegalStateException("not within withRandom(...)");
return r.nextInt((max - min) + 1) + min;
}
}
这样,当前执行模拟的每个线程都可以与
随机的
实例,而尝试访问
随机的
不执行模拟的线程被拒绝,并且一个线程可以一个接一个地执行多个模拟,每个模拟都与不同的
随机的
实例,但不能嵌套模拟。检测到并拒绝嵌套执行的尝试。另一个重要属性是,线程本地值在之后被删除,因此如果线程被重用用于其他目的,则不会留下任何垃圾,这适用于并行流使用的工作线程。
管理
随机的
通过简单地使用任意
Runnable
s来描述可能要求局部随机值的操作。
然后,使用的代码可以是
class YourClass implements Runnable {
public void run() {
ArrayList<Random> randomSeedsList = new ArrayList<>();
int total = getNumberOfSimulations();
for (int run = 0; run < total; run++) {
randomSeedsList.add(new Random(run));
}
assert randomSeedsList.size() == total;
IntStream.range(0, total).parallel()
.forEach(run -> RandomManager.withRandom(randomSeedsList.get(run),
()->runSimulation(run, â¦)));
}
}
或者,如果整数索引仅用于维护与
随机的
实例,您可以进一步简化:
class YourClass implements Runnable {
public void run() {
List<Random> randomSeedsList
= IntStream.range(0, getNumberOfSimulations())
.mapToObj(Random::new)
.collect(Collectors.toList());
randomSeedsList.parallelStream()
.forEach(random -> RandomManager.withRandom(random,
()->runSimulation(â¦)));
}
}