(五)线程--定制线程及设置和获取线程的优先级别
(五)线程--定制线程及设置和获取线程的优先级别 (一).描述
此示例演示怎样定制一个线程,并且设置线程的主要属性和获取线程运行时的状态
(二).代码
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();
}
}
}
本示例代码已经测试,能够正常运行!
(三).示例下载
http://www.cnblogs.com/Files/ChengKing/ThreadExample.rar