C# 线程传参

传参方式有两种:

       1、创建带参构造方法类 传参

       2、利用Thread.start(8)直接传参,该方法会接收一个对象,并将该对象传递给线程,因此在线程中启动的方法

             必须接收object类型的单个参数。

       3、闭包传参 该方法使用lambda表达式。

           3.1 lambda表达式中使用任何局部变量时 ,C# 会自动生成一个类,并将该变量作为该类的一个属性。实际上与第一种方式基本一样,但是我们无需定义类,C#会自动编译实现该类。

           3.2 使用lambda表达式会导致一些问题,如使用多个lambda表达式中使用相同的变量,他们会共享该变量值

 

          

using System;
using System.Threading;

namespace testThread_Transferparameters
{
    class Program
    {
        static void Main(string[] args)
        {
            
            //1
            var sample = new ThreadSample(10);
            var threadone = new Thread(sample.CountNumbers);
            threadone.Name = "ThreadOne";
            threadone.Start();
            threadone.Join();
            Console.WriteLine("------------------");
             
            //2
            var threadtwo = new Thread(count);
            threadtwo.Name = "threadtwo";
            threadtwo.Start(8);
            threadtwo.Join();
            Console.WriteLine("------------------");
            
             //3
            var threadthree = new Thread(() => CountNumbers(20));
            threadthree.Name = "threadthree";
            threadthree.Start();
            threadthree.Join();
            Console.WriteLine("------------------");

            int i = 10;
            var threadfour = new Thread(() => PrintNumber(i));
            i = 20;
            var threadfive = new Thread(() => PrintNumber(i));
            threadfour.Start();
            threadfive.Start();
        }
        static void count(object iterations)
        {
            CountNumbers((int)iterations);
        }
        static void CountNumbers(int iterations)
        {
            for (int i = 1; i <= iterations; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
            }
        }
        static void PrintNumber(int number)
        {
            Console.WriteLine(number);
        }
    }

    class ThreadSample
    {
        private readonly int _iterations;
        public ThreadSample(int iterations)
        {
            _iterations = iterations;
        }
        public void CountNumbers()
        {
            for (int i = 1; i <= _iterations; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
            }
        }
    }
}

 结果如下:

        

 

转载于:https://www.cnblogs.com/ch-lf/p/5709923.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值