java.util.concurrent.ThreadLocalRandom
实例。
ThreadLocalRandom
不应在线程之间共享,因为不具备线程安全。
该检查可以报告分配给用作方法实参的字段,或分配给局部变量并在匿名类或嵌套类中使用的实例,因为它们可能在线程之间共享。
ThreadLocalRandom
的用法通常应类似于ThreadLocalRandom.current().nextInt(...)
(或 nextDouble(...)
等)。
当所有用法都采取这种形式时,ThreadLocalRandom
实例就不会被多个线程误用。
示例:
class Main {
void printRandomNumbersAsync() {
ThreadLocalRandom random = ThreadLocalRandom.current();
CompletableFuture.supplyAsync(() -> generateNumbers(random))
.thenAccept(numbers -> System.out.println(Arrays.toString(numbers)));
}
private int[] generateNumbers(Random random) {
return random.ints(1000, 0, 100).toArray();
}
}
使用这些选项可以列出能够作为实参传递给 ThreadLocalRandom
实例的方法。
可以将正则表达式用于方法名称。