using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;namespace ThreadPriorities
{
class ThreadPriorityTest
{
static void Main()
{
ThreadStart startDelegate = new ThreadStart(ThreadProc);
Console.WriteLine("startup five threads with different priority");
Thread Thread1 = new Thread(startDelegate);
Thread1.Name = ("线程1");
Thread Thread2 = new Thread(startDelegate);
Thread2.Name = ("线程2");
Thread Thread3 = new Thread(startDelegate);
Thread3.Name = ("线程3");
Thread Thread4 = new Thread(startDelegate);
Thread4.Name = ("线程4");
Thread Thread5 = new Thread(startDelegate);
Thread5.Name = ("线程5");
Thread1.Priority = ThreadPriority.Highest;
Thread2.Priority = ThreadPriority.AboveNormal;
Thread3.Priority = ThreadPriority.Normal;
Thread4.Priority = ThreadPriority.BelowNormal;
Thread5.Priority = ThreadPriority.Lowest;
Thread5.Start();
Thread4.Start();
Thread3.Start();
Thread2.Start();
Thread1.Start();
Console.ReadKey(); }
public static void ThreadProc()
{
Thread.Sleep(3000);
Console.WriteLine("\t{0} - {1}", Thread.CurrentThread.Name,
Thread.CurrentThread.Priority);
} }
}
为什么这个程序的多次运行结果并不一致,这是学习线程的优先级时遇到的简单的程序,想要得到的结果很明显,优先级高的先执行,但是结果并不是如此。多次运行结果也都不一致。搜罗一下有人说是线程的同步问题,没看懂,个人认为可能是操作系统的线程调度问题,又不敢确定。请高手给初学者深入浅出的指点一下,谢谢!
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;namespace ThreadPriorities
{
class ThreadPriorityTest
{
static void Main()
{
ThreadStart startDelegate = new ThreadStart(ThreadProc);
Console.WriteLine("startup five threads with different priority");
Thread Thread1 = new Thread(startDelegate);
Thread1.Name = ("线程1");
Thread Thread2 = new Thread(startDelegate);
Thread2.Name = ("线程2");
Thread Thread3 = new Thread(startDelegate);
Thread3.Name = ("线程3");
Thread Thread4 = new Thread(startDelegate);
Thread4.Name = ("线程4");
Thread Thread5 = new Thread(startDelegate);
Thread5.Name = ("线程5");
Thread1.Priority = ThreadPriority.Highest;
Thread2.Priority = ThreadPriority.AboveNormal;
Thread3.Priority = ThreadPriority.Normal;
Thread4.Priority = ThreadPriority.BelowNormal;
Thread5.Priority = ThreadPriority.Lowest;
Thread5.Start();
Thread4.Start();
Thread3.Start();
Thread2.Start();
Thread1.Start();
Console.ReadKey(); }
public static void ThreadProc()
{
Thread.Sleep(3000);
Console.WriteLine("\t{0} - {1}", Thread.CurrentThread.Name,
Thread.CurrentThread.Priority);
} }
}
为什么这个程序的多次运行结果并不一致,这是学习线程的优先级时遇到的简单的程序,想要得到的结果很明显,优先级高的先执行,但是结果并不是如此。多次运行结果也都不一致。搜罗一下有人说是线程的同步问题,没看懂,个人认为可能是操作系统的线程调度问题,又不敢确定。请高手给初学者深入浅出的指点一下,谢谢!
所以高优先级的线程 可能在执行一段时间后挂起(时间不是固定的),转而执行别的线程,
所以每次看到的每次都不太一样。当然因为优先级高的线程被执行的机会比较多,往往先执行完
UP