大家好,又见面了,我是你们的朋友全栈君。
构造有参数的线程就得需要用到ParameterizedThreadStart,查看从元数据可以看出ParameterizedThreadStart是一个委托,参数类型必须是Object类型。
我们通过线程对象的Start方法可以将参数传入,如thread.Start(“20191230”),此时参数“20191230”就会传递给子线程要执行的方法。代码:
class Program
{
static void Main(string[] args)
{
//Thread thread = new Thread(new ParameterizedThreadStart(WorkerA));
Thread thread = new Thread(WorkerA);
thread.Start("20191230");
Console.WriteLine("主程序退出");
}
static void WorkerA(object data) {
Thread.Sleep(1000);
Console.WriteLine("传入的参数:"+data.ToString());
Console.WriteLine("后台程序退出");
}
}
以上代码输出结果为:
既然我们传入的是object类型,那我们也可以传入一个集合或者数组:
static void Main(string[] args)
{
//Thread thread = new Thread(new ParameterizedThreadStart(WorkerA));
Thread thread = new Thread(WorkerA);
List<int> list = new List<int>() { 1, 2, 3 };
thread.Start(list);
Console.WriteLine("主程序退出");
Console.ReadKey();
}
static void WorkerA(object data)
{
List<int> listmy = (List<int>)data;
Thread.Sleep(1000);
for (int i = 0; i < listmy.Count; i++)
{
Console.WriteLine("传入的参数" + listmy[i].ToString());
}
Console.WriteLine("后台程序退出");
}
输出结果为:
Demo链接:https://github.com/wangongshen/Wgs.CSDN.Demo2019
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/159641.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有