C# Thread.Join()


Thread.Join() 官網解釋如下:

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

 

在此實例表示的線程終止前,阻止調用線程。

如下代碼,thread1 是最先運行,但是由於執行 thread2.join() 阻塞了線程,所以必須等到 thread2 線程執行完成后,才會繼續執行 thread1。

也就是:前線程CurThread將被阻塞,直到CalleeThread線程完成后CurThread 剛剛CalleeThread.Join() 的后續代碼才繼續往下執行

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

 

有一篇解釋的還可以的文章:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM