首页 > 技术文章 > 如何控制多线程之间的优先级顺序

xuezha 2015-10-26 16:36 原文

  class Program
    {
        static void Main(string[] args)
        {
            PriorityClass pc = new PriorityClass();  //实例化PriorityTest类
            Thread threadOne = new Thread(new ThreadStart(pc.ThreadMethod));//实例化线程
            threadOne.Name = "线程1"; //设置线程名
            Thread threadTwo = new Thread(new ThreadStart(pc.ThreadMethod));//实列化线程
            threadTwo.Name = "线程2";//设置线程名
            threadTwo.Priority = ThreadPriority.BelowNormal;//设置线程的优先级
            Thread threadThree = new Thread(new ThreadStart(pc.ThreadMethod));//实列化线程
            threadThree.Name = "线程3";//设置线程名
            threadThree.Priority = ThreadPriority.AboveNormal;//设置线程的优先级
            Thread threadFour = new Thread(new ThreadStart(pc.ThreadMethod));//实列化线程
            threadFour.Name = "线程4";//设置线程名
            threadFour.Priority = ThreadPriority.Highest;//设置线程的优先级
            Thread threadFive = new Thread(new ThreadStart(pc.ThreadMethod));//实列化线程
            threadFive.Name = "线程5";//设置线程名
            threadFive.Priority = ThreadPriority.Lowest;//设置线程的优先级
            threadOne.Start();//执行线程
            threadTwo.Start();//执行线程
            threadThree.Start();
            threadFour.Start();
            threadFive.Start();
            Thread.Sleep(1000);//线程休眠1秒
            pc.LoopSwitch = false;
            Console.ReadLine();
        }
        class PriorityClass  //自定义一个类
        {
            bool loopSwitch;   //定义一个布尔型变量
            public PriorityClass()   //构造方法
            {
                loopSwitch = true;
            }
            public bool LoopSwitch
            {
                set { loopSwitch = value; }
            }
            public void ThreadMethod()   //线程执行方法
            {
                long threadCount = 0;
                while (loopSwitch)
                {
                    threadCount++;
                }
                Console.WriteLine("{0} with {1,11} priority" + "has acount ={2,13}", Thread.CurrentThread.Name, Thread.CurrentThread.Priority.ToString(), threadCount.ToString("NO"));//显示当前线程情况
            }
        }

推荐阅读