zoukankan      html  css  js  c++  java
  • C#多线程学习笔记(二)——带参数的多线程

     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 MyThreadfun
    21     {
    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 Program
    32     {
    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连个参数封装成一类,然后对其进行初始化,最后在线程中调用类中的方法即可。
  • 相关阅读:
    Dragon Balls_并查集
    Farm Irrigation_并查集||dfs
    The trouble of Xiaoqian_多重背包&&完全背包
    Difference Is Beautiful
    Bone Collector II_第k大背包
    Dividing_多重背包
    Milk
    coins_多重背包
    钱币兑换问题_完全背包&&拆分&&母函数
    多项式链表多项式相加
  • 原文地址:https://www.cnblogs.com/HighFun/p/2456124.html
Copyright © 2011-2022 走看看