C# 多线程 - 为什么 2 个线程调用同一个函数?

标签 c# .net multithreading visual-studio-2010

我有一个带有 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秒。
threadthread2总是生成相同的时间,如何解决?

最佳答案

您的困惑不是因为线程,而是因为随机数生成器。

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/

相关文章:

c# - 将 SQL 转换为 LINQ

c# - 无法加载文件或程序集,Oracle.DataAccess v 2.112.3.0

c# - 等待空任务永远旋转(等待新任务(()=>{}))

c++ - C++ 队列中的线程池

JAVA(发送音频流 一服务器四客户端同机)

c# - HttpContent.ReadAsAsync 在哪里?

c# - SQLite:创建表并在表不存在时添加一行

c# - IEnumerable 扩展

.net - 是否有像集合这样的字典可以使用其值的属性作为键?

java - Intent 服务并发