C#多线程学习笔记(二)——带参数的多线程

来源:互联网 发布:杜蕾斯网络代理 编辑:程序博客网 时间:2024/06/06 03:53
 1         Thread t; 2         public myThread() 3         { 4             t = new Thread(run); 5             t.Start(2); //这里吧参数传递进去 6             t.Join(); 7              8         } 9         static void run(object obj) //带参数的run函数10         {11             int a = (int)obj;12             Console.WriteLine(a);13 14         }

这种方法只能传递一个单数,当然多个参数可以封装成一个结构体传进去,但是不是好的方法

可以讲要进行元算的元素封装成一个类,然后在然后对这个类进行初始化,最用在线程中调用这个类的函数即可

 1 namespace ThreadPara 2 { 3     class myThread //直接传参数进去 4     { 5         Thread t; 6         public myThread() 7         { 8             t = new Thread(run); 9             t.Start(2);10             t.Join();11             12         }13         static void run(object obj)14         {15             int a = (int)obj;16             Console.WriteLine(a);17 18         }19     }20     class MyThreadfun21     {22         public int a;23         public int b; //通过公共成员来赋值24         public void fun()25         {26             int c = a + b;27             Console.WriteLine(c);28         }29 30     }31     class Program32     {33         static void Main(string[] args)34         {35             myThread mt = new myThread();36             MyThreadfun fun = new MyThreadfun();37             Thread t = new Thread(fun.fun);38             fun.a = 2;39             fun.b = 3;40             t.Start();41 42         }43     }44 }
MyThreadfun 就是讲a b连个参数封装成一类,然后对其进行初始化,最后在线程中调用类中的方法即可。
原创粉丝点击