(一).描述
此示例演示怎样定制一个线程,并且设置线程的主要属性和获取线程运行时的状态
(二).代码
using system;
using system.threading;
namespace 定制线程
{
//委托声明(函数签名)
//delegate string mymethoddelegate();
class myclass
{
public static void method1()
{
int i;
for(i=0;i<10;i++)
{
console.writeline(“method1 at :” + i.tostring());
//当线程停止/失败或未启动时isalive值为:false,否则为:true;
console.writeline(” isalive is ” + thread.currentthread.isalive.tostring()+” “);
//是否是后台进程
console.writeline(” isbackground is ” + thread.currentthread.isbackground.tostring()+” “);
//线程名称
console.writeline(” name is ” + thread.currentthread.name.tostring()+” “);
//优先级
console.writeline(” priority is ” + thread.currentthread.priority.tostring()+” “);
//threadstate值组合,有:启动/运行/等待/是否是后台线程等状态. 通过此属性来判断该线程是否完成任务.
console.writeline(” threadstate is ” + thread.currentthread.threadstate.tostring()+”\n\n “);
delaytime(1); //延长时间,模拟执行任务
}
}
public static void method2()
{
int i;
for(i=0;i<10;i++)
{
console.write(“method2 at :” + i.tostring());
//当线程停止/失败或未启动时isalive值为:false,否则为:true;
console.writeline(” isalive is ” + thread.currentthread.isalive.tostring()+” “);
//是否是后台进程
console.writeline(” isbackground is ” + thread.currentthread.isbackground.tostring()+” “);
//线程名称
console.writeline(” name is ” + thread.currentthread.name.tostring()+” “);
//优先级
console.writeline(” priority is ” + thread.currentthread.priority.tostring()+” “);
//threadstate值组合,有:启动/运行/等待/是否是后台线程等状态. 通过此属性来判断该线程是否完成任务.
console.writeline(” threadstate is ” + thread.currentthread.threadstate.tostring()+”\n\n “);
delaytime(1); //延长时间,模拟执行任务
}
}
private static void delaytime(int n)
{
datetime starttime = datetime.now;
while(starttime.addseconds(n) > datetime.now)
{
//延长时间,模拟实际中的进程
}
}
[stathread]
static void main(string[] args)
{
// mymethoddelegate d1 = new mymethoddelegate(myclass.method1);
// mymethoddelegate d2 = new mymethoddelegate(myclass.method2);
thread thread1 = new thread(new threadstart(method1));
thread1.name = “a”; //给线程定义名称
//threadpriority枚举共五种优先级,由高->低依次为: highest->abovenormal->normal->belownormal->lowest
//优先级高的先优先执行,相同优先级的线程具有相同对cpu争夺权力
thread1.priority = threadpriority.highest;
thread thread2 = new thread(new threadstart(method2));
thread2.name = “b”;
thread2.priority = threadpriority.normal;
thread1.start();
thread2.start();
console.read();
}
}
}
本示例代码已经测试,能够正常运行!
