向线程传递参数

示例

using System;
using System.Threading;
using static System.Console;
using static System.Threading.Thread;

namespace Chapter1.Recipe8
{
	class Program
	{
		static void Main(string[] args)
		{
            //实例化并传参数10
			var sample = new ThreadSample(10);

			var threadOne = new Thread(sample.CountNumbers);
			threadOne.Name = "ThreadOne";
			threadOne.Start();
			threadOne.Join();
			WriteLine("******************************");
			var threadTwo = new Thread(Count);
			threadTwo.Name = "ThreadTwo";
            //传入参数
			threadTwo.Start(8);
			threadTwo.Join();
			WriteLine("******************************");
			var threadThree = new Thread(() => CountNumbers(12));
			threadThree.Name = "ThreadThree";
			threadThree.Start();
			threadThree.Join();
			WriteLine("******************************");
			int i = 10;
			var threadFour = new Thread(() => PrintNumber(i));
			i = 20;
			var threadFive = new Thread(() => PrintNumber(i));
			threadFour.Start(); 
			threadFive.Start();
            Console.ReadKey();
		}
		static void Count(object iterations)
		{
			CountNumbers((int)iterations);
		}
		static void CountNumbers(int iterations)
		{
			for (int i = 1; i <= iterations; i++)
			{
				Sleep(TimeSpan.FromSeconds(0.5));
				WriteLine($"{CurrentThread.Name} prints {i}");
			}
		}
		static void PrintNumber(int number)
		{
			WriteLine(number);
		}
		class ThreadSample
		{
			private readonly int _iterations;

			public ThreadSample(int iterations)
			{
				_iterations = iterations;
			}
			public void CountNumbers()
			{
				for (int i = 1; i <= _iterations; i++)
				{
					Sleep(TimeSpan.FromSeconds(0.5));
                    WriteLine($"{CurrentThread.Name} prints {i}");
                }
			}
		}
	}

	
}

CountNumbers方法运行在两个线程中。程序是静态的,线程是动态的。
除了在创建新的线程时传入参数时,另一种传递数据的方式是使用Thread.Start()方法。该方法会接收一个对象,并将该对象传递给线程。须知,在线程中启动的方法必须接收object类型的单个参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值