在.Net中,Join方法主要是用來阻塞調用線程,直到某個線程終止或經過了指定時間為止。Join方法的聲明如下:
public void Join(); public bool Join(int millisecondsTimeout); public bool Join(TimeSpan timeout);
先看一段簡單的代碼,再來理解Join方法到底是怎么用的,代碼如下:
static void Main() { var stopwatch = Stopwatch.StartNew(); Thread[] array = new Thread[5]; Array.ForEach<Thread>(array, t => { t = new Thread(new ThreadStart(Run)); t.Start(); t.Join(); }); Console.WriteLine("總共使用時間: {0}", stopwatch.ElapsedMilliseconds); Console.Read(); } static void Run() { Thread.Sleep(5000); }
上面的代碼執行的結果大概為25秒鍾,可以推斷線程數組是依次去執行Run()方法的。t.Join()會阻塞執行Main()方法的線程,也就是主線程,直到線程t執行完畢,才會啟動下一個線程,繼續阻塞主線程,直到線程數組全部執行完畢,主線程才會繼續執行,最后輸出總共使用時間。
下面我們稍稍改動代碼,來驗證推斷,修改后的代碼如下:
static void Main() { var stopwatch = Stopwatch.StartNew(); Thread[] array = new Thread[5]; int i = 0; Array.ForEach<Thread>(array, t => { t = new Thread(new ThreadStart(Run)); i++; t.Name = "線程" + i.ToString(); t.Start(); t.Join(); }); Console.WriteLine("總共使用時間: {0}", stopwatch.ElapsedMilliseconds); Console.Read(); } static void Run() { Thread.Sleep(5000); Console.WriteLine("當前線程: {0}", Thread.CurrentThread.Name); }
執行的結果每隔5秒,依次輸出當前線程的名稱,最后輸出總共使用時間25033.
理解了Join()方法,重載版本也就不難理解了。再來看下Join(int millisecondsTimeout)方法,方法摘要為,如果線程已終止,則為 true;如果線程在經過了 millisecondsTimeout 參數指定的時間量后未終止,則為 false。比如上面的代碼使用t.Join(1000),只會阻塞主線程1秒。