zoukankan      html  css  js  c++  java
  • 线程的参数传递

       线程大家都听说过,也或多或少的看到过或使用过。但对于线程中的参数传递可能会比较陌生,今天我在这就跟大家分享下线程的传递方法。

       在分享线程的参数传递方法之前我们先来看看不带参的线程:

       using System.Threading;(在使用线程前别忘记了加上命名空间)

       public class threadclass

       {

           public static void getThread()

          {

                Thread thread=new Thread(T);//Thread thread=new Thread(new ThreadStart(T));//两句效果相同

                thread.start();

          }

          public string T()

          { 

               return 0;

           }

       }

       上面的代码是在threadclass类中以一个getThread()函数去使用线程;不知道大家有没有留意到类中函数的第一行的注释,在注释里面有个ThreadStart;

       在线程中ThreadStart主是用来定义不带参的线程,这也是我们经常用到的一个方法。

       接下来我们来看看带参数传递的线程:

       

       using System.Threading;(在使用线程前别忘记了加上命名空间)

       public class threadclass

       {

           public static void getThread()

          {

                Thread thread=new Thread(new ParameterizedThreadStart(T));

                thread.start(10);

          }

          public string T(object i)

          { 

              string str=i.Tostring();

               return str;

           }

       }

       我们来比较下和不带参数的线程使用有什么区别:

       1.不带参的线程是使用ThreadStart来定义的,而带参数传递的线程是用parameterizedThreadStart定义;

      2.线程所调用的方法一个没有带任何参数另一个带有一个object参数;

      3.在启用线程(Start())时,其中带参数传递的线程是有参数的,而不带参的就没有。

       从这些区别中我们能来做个总结,在使用不带参的线程时用ThreadStart来定义线程,带参数传递的线程是用parameterizedThreadStart定义;线程带参传递时是用Start来传递。

       现在让我们一起来了解下ParameterizdeThreadStart,在使用ParameterizedThreadStart定义的线程中,线程可以接受一个object参数,但必须中有一个在多就不行;所以在带参数的线程中调用的方法只有一个object参数。

    到这里可能有人会问,如果我要传递两个或两个以上应该怎么办,带参数传递的线程方法就只能传递一个参数;哪不是没用外不大吗?下面我给大家一种传递两个参数的方法,代码如下:

      using System.Threading;(在使用线程前别忘记了加上命名空间)

       public class threadclass

       {

           public static void getThread()

          {

                Thread thread=new Thread(new ParameterizedThreadStart(T));

                thread.start(10);

          }

          public string T(object i)

          { 

              string str=i.Tostring();

              string b="你好";

              string S=T2(str,b);

               return S;

           }

          public string T2(string i,string j)

          {

            string s=i+","+j+"";

             return  s;

          }

       }

  • 相关阅读:
    19年下半年读书清单一览
    2019-2020:时间戳
    全链路压测资料汇总——业内大厂解决方案
    个人公众号开通啦
    windows 10环境下安装Tensorflow-gpu
    如何判断安卓模拟器的型号(品牌)
    socket.io的websocket示例
    Node + Selenium使用小结
    基于SOUI开发一个简单的小工具
    国际化之Android设备支持的语种
  • 原文地址:https://www.cnblogs.com/ljhboke/p/5038497.html
Copyright © 2011-2022 走看看