Multithrading
Multithrading
// Driver Class
public class XYZ {
// Main Method
static public void Main()
{
// Calling static methods
ABC.method1();
ABC.method2();
}
}
Output:
Method1 is : 0
Method1 is : 1
Method1 is : 2
Method1 is : 3
Method1 is : 4
Method1 is : 5
Method1 is : 6
Method1 is : 7
Method1 is : 8
Method1 is : 9
Method1 is : 10
Method2 is : 0
Method2 is : 1
Method2 is : 2
Method2 is : 3
Method2 is : 4
Method2 is : 5
Method2 is : 6
Method2 is : 7
Method2 is : 8
Method2 is : 9
Method2 is : 10
Explanation: Here, first of all, method1 executes. In method1 , for loop starts
from 0 when the value of i is equal to 5 then the method goes into sleep for 6
seconds and after 6 seconds it resumes its process and print remaining value.
Until method2 is in the waiting state. method2 start its working
when method1 complete its assigned task. So to overcome the drawback of
single threaded model multithreading is introduced.
Example:
// Main Method
static public void Main()
{
Output :
Method1 is : 0
Method1 is : 1
Method1 is : 2
Method1 is : 3
Method2 is : 0
Method2 is : 1
Method2 is : 2
Method2 is : 3
Method2 is : 4
Method2 is : 5
Method2 is : 6
Method2 is : 7
Method2 is : 8
Method2 is : 9
Method2 is : 10
Method1 is : 4
Method1 is : 5
Method1 is : 6
Method1 is : 7
Method1 is : 8
Method1 is : 9
Method1 is : 10
Explanation: Here, we create and initialize two threads, i.e thr1 and thr2 using
Thread class. Now using thr1.Start(); and thr2.Start(); we start the
execution of both the threads. Now both thread runs simultaneously and the
processing of thr2 does not depend upon the processing of thr1 like in the
single threaded model.
Note: Output may vary due to context switching.
Advantages of Multithreading:
It executes multiple process simultaneously.
Maximize the utilization of CPU resources.
Time sharing between multiple process.
t1.Priority = ThreadPriority.Lowest;
or
t1.Priority = ThreadPriority.Highest;
or
t1.Priority = ThreadPriority.AboveNormal;
or
t1.Priority = ThreadPriority.Lowest;
Thread Life Cycle
The life cycle of a thread starts when an object of the
System.Threading.Thread class is created and ends when the
thread is terminated or completes execution.
namespace MultithreadingApplication {
class MainThreadProgram {
static void Main(string[] args) {
Thread th = Thread.CurrentThread;
th.Name = "MainThread";
This is MainThread