线程的两种启动方式

1、没有参数的启动方式:

 using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace MoreThead
{
    class TheadProgram
    {
        Thread th;
        static void Main(string[] args)
        {
            TheadProgram tp = new TheadProgram();
            tp.RunThread();
        }

        private void RunThread()
        {
            //启动一个不带参数的线程
            th = new Thread(new ThreadStart(Sum));
            th.Start();
        }

        private void Sum()
        {
            //一个简单的加一操作
            int iBegin = 0;
            iBegin++;
            Console.Write("{0}", iBegin);
        }
    }
}

2、含参数的启动方式:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace MoreThead
{
    class TheadProgram
    {
        Thread th;
        static void Main(string[] args)
        {
            TheadProgram tp = new TheadProgram();
            tp.RunThread();
        }

        private void RunThread()
        {
            //启动一个带参数的线程
            th = new Thread(new ParameterizedThreadStart(Sum));
            th.Start(5);
        }

        private void Sum(object obj)  //注意这里的参数类型要为 object;可以在方法体内把参数转化成实际的类型
        {
            //一个简单的加一操作
            int iBegin = int.Parse(obj.ToString());
            iBegin++;
            Console.Write("{0}", iBegin);
        }
    }
}

posted on 2009-12-07 21:55  tigerhuolh  阅读(386)  评论(0编辑  收藏  举报

导航