join in multithreading |
JOIN METHOD IN MULTITHREADING IN C#
“Join is the keyword which is used in multi-threading, when the Main Thread
need to stay in program until the child threads does not complete their task”.
Syntax of Join method
<Thread-instance>
Join ( );
In between the brackets you can also
specify the time to allow the Main thread go away from the program, if the
specific thread does not complete its task in given time. Like
<Thread-instance>
Join (4000);
Why we use Join method in multithreading?
In
different project we have to make multiple child threads to execute different
block of code as needed, but what happen in this process the Main Thread which
is responsible to execute the entire program going to make child threads and
itself exits form program, thus we want to stay the Main Thread until the child
threads complete their task, we want that the Main thread should exist after
all the child threads exited.
Example of join method in c#
namespace ThraedLock
{
static class Muliplethread
{
public static void Testmethod1()
{
Console.WriteLine("Thread 1
starting");
for (int i=1;i<100;i++)
Console.WriteLine("Testmethod1:
line no" + i);
Console.WriteLine("Thread 1
exiting");
}
public static void Testmethod2()
{
Console.WriteLine("Thread 2
starting");
for (int i = 1; i < 100; i++)
Console.WriteLine("Testmethod2:
line no" + i);
Console.WriteLine("Thread 2
exiting");
}
public static void Testmethod3()
{
Console.WriteLine("Thread 3
starting");
for (int i = 1; i < 100; i++)
Console.WriteLine("Testmethod3:
line no" + i);
Console.WriteLine("Thread 3
exiting");
}
static void Main()
{
Console.WriteLine("Mian thread
starting");
Thread t1 = new Thread(Testmethod1);
Thread t2 = new Thread(Testmethod2);
Thread t3 = new Thread(Testmethod3);
t1.Start(); t2.Start(); t3.Start();
t1.Join(); t2.Join();t3.Join();
Console.WriteLine("Mian thread
exiting");
Console.ReadKey();
}
}
}
Here when we use Join with
the threads the Main thread will exit from the program after exiting all the child
threads.
0 comments:
Post a Comment
Please do not enter any spam link in the comment box