以下我們可以觀察到一般的執行結果如下:
- 在多核心的情況下:優先序較高者,計算的count數較高
- 在單核心的情況下:優先序較高者先執行,優先序低者還沒執行Stop已經被呼叫了
程式代碼如下:
using System;
using System.Diagnostics;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
/** *******************
* 測試Thread的優先序
* ********************/
Console.WriteLine($"priority: {Thread.CurrentThread.Priority}");
Console.WriteLine("----");
Console.WriteLine($"multi-core:");
RunThread();
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("----");
Console.WriteLine($"single-core:");
//讓系統只在單一CPU上運行
Process.GetCurrentProcess().ProcessorAffinity = new IntPtr(1);
RunThread();
}
static void RunThread()
{
var sample = new ThreadSample();
var t1 = new Thread(sample.CountNumbers);
var t2 = new Thread(sample.CountNumbers);
t1.Name = "Thread One";
t2.Name = "Thread Two";
//指定t1有最高優先權
t1.Priority = ThreadPriority.Highest;
//指定t2有最低優先權
t2.Priority = ThreadPriority.Lowest;
t1.Start();
t2.Start();
Thread.Sleep(TimeSpan.FromSeconds(2));
sample.Stop();
}
}
class ThreadSample
{
private bool _isStop = false;
public void Stop()
{
_isStop = true;
}
public void CountNumbers()
{
long count = 0;
while(!_isStop)
{
count++;
}
//看執行緒記算了多少count,觀察優先序的影響
Console.WriteLine($@"{Thread.CurrentThread.Name}
with {Thread.CurrentThread.Priority} priority
has a count = {count}");
}
}
}