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;

          }

       }

  • 相关阅读:
    CentOS忘记密码修改方案以及centos卡在开机登录界面,命令失效的解决方法
    音乐制作模块
    CentOS7安装RabbitMQ,并设置远程访问
    设计模式
    排序
    经典排序算法及python实现
    scrapy初步解析源码即深度使用
    JAVA----线程初级
    Python随笔--魔法方法(析构与构造)
    Python随笔--对象
  • 原文地址:https://www.cnblogs.com/ljhboke/p/5038497.html
Copyright © 2011-2022 走看看