我有一个带有 2 个线程的 C# 代码。它调用 print 方法,但它总是有相同的时间.. 为什么?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace MultiThreading
{
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(new ThreadStart(new Program().print));
Thread thread2 = new Thread(new ThreadStart(new Program().print));
thread.Name = "Thread1";
thread2.Name = "thread2";
thread.Start();
thread2.Start();
}
public void print()
{
Random r = new Random();
int time = r.Next(3000);
System.Console.WriteLine(Thread.CurrentThread.Name + ", " + (double)time/1000 + " secs!");
Thread.Sleep(time);
}
}
}
好的,所以我有 2 个线程,每个线程都有“打印”委托(delegate)。
print 生成一个数字
time
什么什么time
秒。thread
和 thread2
总是生成相同的时间,如何解决?
最佳答案
您的困惑不是因为线程,而是因为随机数生成器。
MSDN 说:
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random.
尝试用这个替换你的新随机线,看看有什么不同。
Random r = new Random(Thread.CurrentThread.ManagedThreadId);
我刚刚添加了一个新的随机种子,以便每个线程都获得不同的值。
编辑:除了 ManagedThreadId,您可以使用您选择的任何其他值作为种子值。您需要确保从 Random 对象中获取不同的随机数序列是不同的。至于为什么 ManagedThreadId 不是一个很好的选择,请看下面的评论。
关于C# 多线程 - 为什么 2 个线程调用同一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14051144/