PriorityThreadpt=newPriorityThread();Threadt1=newThread(newThreadStart(pt.thread));Threadt2=newThread(newThreadStart(pt.thread));Threadt3=newThread(newThreadStart(pt.thread));t1.Name="MongoDB";t2.Name="Cassendra";t3.Name="MySQL";t2.Priority=ThreadPriority.Highest;t3.Priority=ThreadPriority.Normal;t1.Priority=ThreadPriority.Lowest;t1.Start();t2.Start();t3.Start();publicclassPriorityThread{publicvoidthread(){Threadt=Thread.CurrentThread;Console.WriteLine(t.Name+" Server Is Running");}}
Explanation:
In this program, we have created one class named PriorityThread, and in the main method, we have created the objects of PriorityThread and Thread class, and passed those objects as an argument in ThreadStart delegate. With the help of Priority property and ThreadPriority Enum, we set the priority of threads. There are five fields available to set the thread priorities: AboveNormal 3, BelowNormal 1, Highest 4, Lowest 0, and Normal 2.
The high priority thread can be executed first. But it is uncertain that the high priority thread gets executed first as the threads are highly system dependent. Lastly, we have used the Start() method of Thread class to begin the execution. Technically, the thread will move from ready-to-run state to runnable state.
Output
kodingwindow@kw:~/csharp$ dotnet run
MongoDB Server Is Running
Cassendra Server Is Running
MySQL Server Is Running
kodingwindow@kw:~/csharp$
Dear User, Thank you for visitng KodingWindow. If you are interested in technical articles, latest technologies, and our journey further, please follow us on LinkedIn.