Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
Pulic Statc Void Main()
{
Thread t1 = new Thread(SampleClass.StaticMethod1);
t1.Start();

Thread t2 = new Thread(SampleClass.StaticMethod2);
t2.Start();

t1.Join();
t2.join();

Console.Writeline("Main method Completed");
}

Pulic Statc Void StaticMethod1()
{
Thread.Sleep(10000)
Console.Writeline("StaticMethod1 Completed");
}

Pulic Statc Void StaticMethod2()
{
Console.Writeline("StaticMethod2 Completed")
}




When running the above code why does thread2 join is waiting for thread1 to join.
As far i know main thread will wait for thread1 to join but not other threads ?

What I have tried:

I have tried running the above code in different ways all it doing is same.
Posted
Updated 27-May-18 4:19am
Comments
[no name] 27-May-18 10:12am    
See here: Thread.Join Method (System.Threading)[^]
In Remarks you find this: "Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed"

Therefore t1.Join(); blocks the calling thread

1 solution

Correcting your spelling and other syntax errors (in future, copy and paste your code - it makes it easier for everybody):
class SampleClass
    {
    public static void Main()
        {
        Thread t1 = new Thread(SampleClass.StaticMethod1);
        t1.Start();

        Thread t2 = new Thread(SampleClass.StaticMethod2);
        t2.Start();

        t1.Join();
        t2.Join();

        Console.WriteLine("Main method Completed");
        Console.ReadLine();
        }

    public static void StaticMethod1()
        {
        Thread.Sleep(10000);
        Console.WriteLine("StaticMethod1 Completed");
        }

    public static void StaticMethod2()
        {
        Console.WriteLine("StaticMethod2 Completed");
        }
    }
I get the following:
StaticMethod2 Completed
The thread 0x70c has exited with code 259 (0x103).
StaticMethod1 Completed
The thread 0x36c0 has exited with code 259 (0x103).
Main method Completed
Which is exactly what I expect.
I'd check your actual code, and compare it to what is above. If it's the same, then copy and paste it and the results so we can see exactly what you are experiencing.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900