线程操作主要用到thread类,他是定义在system.threading.dll下。使用时需要添加这一个引用。该类提供给我们四个重载的构造函数(以下引自msdn)。
thread (parameterizedthreadstart) 初始化 thread 类的新实例,指定允许对象在线程启动时传递给线程的委托。
thread (threadstart) 初始化 thread 类的新实例。
thread (parameterizedthreadstart, int32) 初始化 thread 类的新实例,指定允许对象在线程启动时传递给线程的委托,并指定线程的最大堆栈大小。
thread (threadstart, int32) 初始化 thread 类的新实例,指定线程的最大堆栈大小。
我们如果定义不带参数的线程,可以用threadstart;带一个参数的用parameterizedthreadstart。带多个参数的用另外的方法,下面逐一讲述。
一、不带参数的
using system;
using system.collections.generic;
using system.text;
using system.threading;
namespace aaaaaa
{
class aaa
{
public static void main()
{
thread t = new thread(new threadstart(a));
t.start();
console.read();
}
private static void a()
{
console.writeline("method a!");
}
}
}
二、带一个参数的
由于parameterizedthreadstart要求参数类型必须为object,所以定义的方法b形参类型必须为object。
using system;
using system.collections.generic;
using system.text;
using system.threading;
namespace aaaaaa
{
class aaa
{
public static void main()
{
thread t = new thread(new parameterizedthreadstart(b));
t.start("b");
console.read();
}
private static void b(object obj)
{
console.writeline("method {0}!",obj.tostring ());
}
}
}
结果显示method b!
三、带多个参数的
由于thread默认只提供了这两种构造函数,如果需要传递多个参数,我们可以自己将参数作为类的属性。定义类的对象时候实例化这个属性,然后进行操作。
using system;
using system.collections.generic;
using system.text;
using system.threading;
namespace aaaaaa
{
class aaa
{
public static void main()
{
my m = new my();
m.x = 2;
m.y = 3;
thread t = new thread(new threadstart(m.c));
t.start();
console.read();
}
}
class my
{
public int x, y;
public void c()
{
console.writeline("x={0},y={1}", this.x, this.y);
}
}
}
结果显示x=2,y=3
四、利用结构体给参数传值。
定义公用的public struct结构体,里面可以定义自己需要的参数,然后在需要添加线程的时候,可以定义结构体的实例。
//结构体
struct rowcol
{
public int row;
public int col;
};
//定义方法
public void output(object rc)
{
rowcol rowcol = (rowcol)rc;
for (int i = 0; i < rowcol.row; i++)
{
for (int j = 0; j < rowcol.col; j++)
console.write("{0} ", _char);
console.write("/n");
}
}
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!
网友评论