我们来看下面的一个例子,演示如何改变线程的优先级。高优先级线程优先执行。但是不能完全保证,因为线程是高度依赖系统的。它只提高了优先级较高的线程在低优先级线程之前执行的机会。
using system;
using system.threading;
public class mythread
{
public void thread1()
{
for(int i=0; i<3; i++)
{
thread t = thread.currentthread;
console.writeline(t.name + " is running");
}
}
}
public class threadexample
{
public static void main()
{
mythread mt = new mythread();
thread t1 = new thread(new threadstart(mt.thread1));
thread t2 = new thread(new threadstart(mt.thread1));
thread t3 = new thread(new threadstart(mt.thread1));
t1.name = "highest-thread ";
t2.name = "normal-thread ";
t3.name = "lowest-thread ";
t1.priority = threadpriority.highest;
t2.priority = threadpriority.normal;
t3.priority = threadpriority.lowest;
t1.start();
t2.start();
t3.start();
}
}
输出是不可预测的,因为线程系统依赖性高。它可以遵循任何算法抢先或非抢占式来执行。
执行上面示例代码,得到以下结果 -
highest-thread is running
normal-thread is running
normal-thread is running
normal-thread is running
lowest-thread is running
lowest-thread is running
lowest-thread is running
highest-thread is running
highest-thread is running