线程的优先级

来源:互联网 发布:血族结局 知乎 编辑:程序博客网 时间:2024/04/27 13:48

//线程是靠CPU时间片来运行的,哪个线程抢的时间片多,他就执行的快。线程的优先级表示线程抢CPU时间片的能力大小。

 以下例子,简单描述了优先级的作用,但效果不是十分明显,偶尔还会效果相反。

 

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Threading;namespace WindowsApplication1{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)        {            PriortyTest work = new PriortyTest(this);            //创建线程并设置线程执行方法            Thread threadOne = new Thread(new ThreadStart(work.ThreadMethod));            threadOne.Name = "线程1";            Thread threadTwo = new Thread(new ThreadStart(work.ThreadMethod));            threadTwo.Name = "线程2";            //设置优先级 这个例子最关健的代码。            threadOne.Priority = ThreadPriority.Highest; //抢CPU时间的能力强,数的数就多一些            threadTwo.Priority = ThreadPriority.BelowNormal;            threadOne.Start();            threadTwo.Start();            //让两个线程都计算1秒钟            Thread.Sleep(1000);            //停止计算            work.LoopSwitch = false;        }    }    /// <summary>    /// 优先级测试类    /// </summary>    public class PriortyTest    {        //用来控制while循环,为false就退出while循环        bool loopSwithch;        Form1 main = null;        //构造方法        public PriortyTest(Form1 _main)        {            main = _main;            loopSwithch = true;        }        /// <summary>        /// 设置循环开关属性        /// </summary>        public bool LoopSwitch        {            set { loopSwithch = value; }        }        /// <summary>        /// 数数方法,并显示出来        /// </summary>        public void ThreadMethod()        {            long threadCount = 0;            //进行累加操作            while (loopSwithch) { threadCount++; }            //结束记数后,显示数到多少了。            show(threadCount.ToString(), Thread.CurrentThread.Name);        }        /// <summary>        ///  向主界面richTextBox1显示信息,        /// </summary>        /// <param name="message">要显示的信息</param>        /// <param name="threadname">当前线程的名字</param>        private void show(string message, string threadname)        {            //richTextBox1控件的Modifiers属性要设为Public,这样才可以调用的到            main.richTextBox1.Invoke(new EventHandler(delegate            {                if (main.richTextBox1.Text.Length > 5069) main.richTextBox1.Clear();                main.richTextBox1.Text += threadname + ":" + message + Environment.NewLine;                main.richTextBox1.Select(main.richTextBox1.Text.Length, 0);                main.richTextBox1.ScrollToCaret();            }));        }    }}