您的位置:首页 > 其它

线程的两种启动方式

2009-12-07 21:55 330 查看
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);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: