Browse Source

[bug修复] 修复多线程下ThreadLocalRandom共享seed导致随机数一样,权重概率bug

yichengxian 5 years ago
parent
commit
7893cfe014
1 changed files with 3 additions and 2 deletions
  1. 3 2
      hutool-core/src/main/java/cn/hutool/core/lang/WeightRandom.java

+ 3 - 2
hutool-core/src/main/java/cn/hutool/core/lang/WeightRandom.java

@@ -32,7 +32,7 @@ public class WeightRandom<T> implements Serializable {
 	private static final long serialVersionUID = -8244697995702786499L;
 
 	private final TreeMap<Double, T> weightMap;
-	private final Random random;
+
 
 	/**
 	 * 创建权重随机获取器
@@ -50,7 +50,7 @@ public class WeightRandom<T> implements Serializable {
 	 */
 	public WeightRandom() {
 		weightMap = new TreeMap<>();
-		random = RandomUtil.getRandom();
+
 	}
 
 	/**
@@ -141,6 +141,7 @@ public class WeightRandom<T> implements Serializable {
 		if(MapUtil.isEmpty(this.weightMap)) {
 			return null;
 		}
+		final Random random = RandomUtil.getRandom();
 		final double randomWeight = this.weightMap.lastKey() * random.nextDouble();
 		final SortedMap<Double, T> tailMap = this.weightMap.tailMap(randomWeight, false);
 		return this.weightMap.get(tailMap.firstKey());