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
有一篇解释的还可以的文章: