C# Thread.Join()

Thread.Join () official website explained as follows:

https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.thread.join?view=netframework-4.8

 

Before thread in this instance represents the termination block the calling thread.

The following code, thread1 is the first run, but due to the implementation of thread2.join () blocks the thread, the thread must wait until after thread2 execution is completed, will continue thread1.

That is: before CurThread thread will be blocked until after CalleeThread thread finishes CurThread just CalleeThread.Join () the subsequent code execution before continuing down

using System;
using System.Threading;

public class Example
{
   static Thread thread1, thread2;
   
   public static void Main()
   {
      thread1 = new Thread(ThreadProc);
      thread1.Name = "Thread1";
      thread1.Start();
      
      thread2 = new Thread(ThreadProc);
      thread2.Name = "Thread2";
      thread2.Start();   
   }

   private static void ThreadProc()
   {
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      if (Thread.CurrentThread.Name == "Thread1" && 
          thread2.ThreadState != ThreadState.Unstarted)
         thread2.Join();
      
      Thread.Sleep(4000);
      Console.WriteLine("\nCurrent thread: {0}", Thread.CurrentThread.Name);
      Console.WriteLine("Thread1: {0}", thread1.ThreadState);
      Console.WriteLine("Thread2: {0}\n", thread2.ThreadState);
   }
}
// The example displays output like the following:
//       Current thread: Thread1
//       
//       Current thread: Thread2
//       
//       Current thread: Thread2
//       Thread1: WaitSleepJoin
//       Thread2: Running
//       
//       
//       Current thread: Thread1
//       Thread1: Running
//       Thread2: Stopped

 

There is an explanation of the article can also:

https://www.cnblogs.com/slikyn/articles/1525940.html

Guess you like

Origin www.cnblogs.com/ryanzheng/p/10962468.html