C# 模拟并发线程(在同一资源/方法上)

C# 模拟并发线程(在同一资源/方法上),c#,multithreading,C#,Multithreading,我在一个简单的并发线程示例中模拟了两个线程可以同时启动同一个方法,并且处理过程在这两个线程之间混合,这有什么方法吗 在下面的例子中,我想看到如下内容: 1 thread1 1 thread2 2 thread1 2 thread2 .. 10 thread1 10 thread2 相反,我得到的是: 1 thread1 2 thread1 ... 10 thread1 1 thread2 2 thread2 ... 10 thread2 好心点,我才刚开始学线呢 简而言之,我想模拟两个线程同

我在一个简单的并发线程示例中模拟了两个线程可以同时启动同一个方法,并且处理过程在这两个线程之间混合,这有什么方法吗

在下面的例子中,我想看到如下内容:

1 thread1
1 thread2
2 thread1
2 thread2
..
10 thread1
10 thread2
相反,我得到的是:

1 thread1
2 thread1
...
10 thread1
1 thread2
2 thread2
...
10 thread2
好心点,我才刚开始学线呢

简而言之,我想模拟两个线程同时启动的效果,而不是一个线程紧接着另一个线程

在完成上述操作之后,我想使用锁,以便thread1在启动thread2之前完全完成执行。在我的示例中,甚至在使用lock之前就已经发生了这种情况

using System;
using System.Threading;

    public class Program
    {
        public class C1
        {

            private object obj = new object();


            public void Ten() 
            {
                //lock(obj)
                //{
                    for(int i=1; i<=10; i++)
                    {
                        Console.WriteLine(i + " " + Thread.CurrentThread.Name);
                    }
                //}
            }

        }
        public static void Main()
        {
            Thread t1 = new Thread(new ThreadStart(new C1().Ten));
            Thread t2 = new Thread(new ThreadStart(new C1().Ten));

            t1.Name = "thread1";
            t2.Name = "thread2";

            t1.Start(); 
            t2.Start();
        }
}
使用系统;
使用系统线程;
公共课程
{
公共类别C1
{
私有对象obj=新对象();
公共图书馆
{
//锁(obj)
//{

对于注释中提到的(int i=1;ias
ESG
),代码运行速度太快。这就是您无法获得预期输出的原因。请尝试在循环中添加一些睡眠以获得预期结果

using System;
using System.Threading;

    public class Program
    {
        public class C1
        {

            private static object obj = new object();


            public void Ten() 
            {
                //lock(obj)
                //{
                    for(int i=1; i<=10; i++)
                    {
                        Console.WriteLine(i + " " + Thread.CurrentThread.Name);
                        Thread.Sleep(1000); //<-- add sleep
                    }
                //}
            }

        }
        public static void Main()
        {
            Thread t1 = new Thread(new ThreadStart(new C1().Ten));
            Thread t2 = new Thread(new ThreadStart(new C1().Ten));

            t1.Name = "thread1";
            t2.Name = "thread2";

            t1.Start(); 
            t2.Start();
        }
}
使用系统;
使用系统线程;
公共课程
{
公共类别C1
{
私有静态对象obj=新对象();
公共图书馆
{
//锁(obj)
//{

对于(int i=1;i)您的循环可能太快了。您尝试过添加延迟/睡眠吗?是的,谢谢我尝试过在t1.Start()之后添加ESG.Thread.sleep(5000);致命错误:已超过执行时间限制。但我现在只能访问在线小提琴手,所以可能这就是原因。我会在可以访问VS并告诉您时重试。非常感谢RajN。使用您的代码,我得到:1 thread1 thread2句号。是否有任何技巧可以继续执行其余步骤直到10?(注意,我正在使用在线小提琴手进行测试,不确定这是否导致了这种行为)