C#多线程详解(二)

在上一节介绍了线程的基础知识,下面来研究多线程的优先级

using System;

using System.Threading;

namespace Test
{
    class TestThread
    {
        private static void FirstThreadFun()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(Thread.CurrentThread.Name + "   i =  " + i);
            }
            Console.WriteLine(Thread.CurrentThread.Name + "的优先级:" + Thread.CurrentThread.Priority);
            Console.WriteLine(Thread.CurrentThread.Name + " 执行完毕");
        }

        private static void SecondThreadFun()
        {
            for (int j = 0; j < 10; j++)
            {
                Console.WriteLine(Thread.CurrentThread.Name + "   j =  " + j);
            }
            Console.WriteLine(Thread.CurrentThread.Name + "的优先级:" + Thread.CurrentThread.Priority);
            Console.WriteLine(Thread.CurrentThread.Name + " 执行完毕");
        }

        static void Main(string[] args)
        {
            //程序调用了Main()函数时,就起动了一个进程,同时也启动了一个线程[这个线程就是主线程].

            Thread.CurrentThread.Name = "MainThread";

 

    //创建第二个线程

            Thread secondThread = new Thread(new ThreadStart(TestThread.SecondThreadFun));
            //取名为 secondThread
            secondThread.Name = "secondThread";
            //设定线程的优先级为AboveNormal[在所有创建的新线程中,执行顺序为第二]

            secondThread.Priority = ThreadPriority.AboveNormal;

 

    //创建第一个线程
            Thread firstThread = new Thread(new ThreadStart(TestThread.FirstThreadFun));
            //取名为 firstThread
            firstThread.Name = "firstThread";
            //设定线程的优先级为最高级[在所有创建的新线程中,最先执行.线程优先级默认为Normal,共5 级:Highest,AboveNormal,Normal,BelowNormal,Lowest]

            firstThread.Priority = ThreadPriority.Highest;

 


            for (int z = 0; z < 20; z++)
            {
                if (z == 10)
                {
                    firstThread.Start();
                    firstThread.Join();

                    secondThread.Start();
                    secondThread.Join();
                }
                else
                {
                    Console.WriteLine(Thread.CurrentThread.Name + "   z =  " + z);
                }
            }
            Console.Read();
        }
    }

}

运行结果:

 

 运行结果显示:

1.主线程永远是最先执行的,但当新线程启动[Thread.Start()],并加入[Thread.Join()]后,主线程会暂停.

2.创建的两个新线程 firstThread 和 secondThread , firstThread的优先级被设为最高 Highest , secondThread的优先级被设为第二.

3.启动和加入也是按顺序的启动 firstThread 先启动加入, secondThread 紧随其后.

4.如果将 firstThread secondThread 的启动[Thread.Start()]顺序调换后会是什么结果?[下节讨论]

 

线程的优先级

当线程之间争夺CPU时间时,CPU 是按照线程的优先级给予服务的。在C#应用程序中,用户可以设定5个不同的优先级,由高到低分别是Highest,AboveNormal,Normal,BelowNormal,Lowest,在创建线程时如果不指定优先级,那么系统默认为ThreadPriority.Normal。

给一个线程指定优先级,我们可以使用如下代码:
//设定优先级为最低
myThread.Priority=ThreadPriority.Lowest;

通过设定线程的优先级,我们可以安排一些相对重要的线程优先执行,例如对用户的响应等等。

 

 

posted on 2010-01-14 17:24  bicabo  阅读(1380)  评论(2编辑  收藏  举报

导航