可能重复:
why does this method return the same random string each time?
Random not that random
我在这段代码中有奇怪的行为。
public void InitPopulation()
{
for (int i = 0; i < PopSize; i++)
{
var builder = new StringBuilder();
var random = new Random();
for (int j = 0; j < Target.Length; j++)
{
builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));
}
vector.Add(new GaStruct() { Fitness = 0, StrValue = builder.ToString().ToLower() });
builder.Clear();
}
}
这段代码给了我5个完全相同的字符串!
如果我像这样添加Thread.Sleep
:
public void InitPopulation()
{
for (int i = 0; i < PopSize; i++)
{
var builder = new StringBuilder();
var random = new Random();
for (int j = 0; j < Target.Length; j++)
{
builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));
}
**System.Threading.Thread.Sleep(20);**
vector.Add(new GaStruct() { Fitness = 0, StrValue = builder.ToString().ToLower() });
builder.Clear();
}
}
一切都很好,所有字符串都是随机的。