当前位置: 移动技术网 > IT编程>开发语言>.net > C#多线程——优先级

C#多线程——优先级

2018年09月23日  | 移动技术网IT编程  | 我要评论

连云港电视台,惠颂玲,常州装潢公司

       在我的公司这里,因为要跟很多特殊的设备打交道,所以会用到多线程的东西,那么我们在进行多线程处理的时候,怎么去设置优先级

我这里用听歌和下载小说做了个例子,我们用电脑的时候肯定是可以边听歌边下载小说的,那么这就需要并行,有个问题就是我想优先听

歌,下载小说对我来说不是那么急的话我就可以对两个事情进行优先级的管控。

        线程里有个属性priority可以用来设置优先级,我设置线程1的优先级高于线程2的优先级,那么线程1就会比线程2多运行一段时间,这个是人眼观察不出来的

运行速度,cpu运行速度可不是能用人眼查看的

            bool b = true;
            int i=0, j=0;
            string song = "";
            string download = "";
            thread thread1=new thread(() =>
            {
                while (b)
                {
                    song="一百万个可能";
                    i++;
                    
                }
            })
            {
                name = "thread1",
                priority = threadpriority.highest
            };
             thread thread2=new thread(() =>
            {
                while (b)
                {
                    download = "小说三体";
                    j++;
                }
            })
            {
                name = "thread2",
                priority = threadpriority.lowest
            };
            thread1.start();
            thread2.start();
            thread.sleep(1000);
            b = false;
            console.writeline("song: {0}, download: {1}", song, download);
            console.writeline("歌曲的优先级:{0}",i);
            console.writeline("下载的优先级:{0}",j);
            console.readline();

这里我们看一下执行结果

从结果中可以看到,优先级高的线程得到运行的次数比优先级低的线程多,但即使是最低优先级的线程都有很大的机会来执行。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网