Thread.Join()用法的理解
// Blocks the calling thread until a thread terminates
指在一線程裡面調用另一線程join方法時,表示將本線程阻塞直至另一線程終止時再執行
比如
class Program
{
static void Main()
{
System.Threading.Thread x = new System.Threading.Thread(new System.Threading.ThreadStart(f1));
x.Start();
Console.WriteLine("This is Main.{0}", 1); // 第一
x.Join(); // 主線程等待x結束
Console.WriteLine("This is Main.{0}", 2); // 第四
Console.ReadLine();
}
static void f1()
{
System.Threading.Thread y = new System.Threading.Thread(new System.Threading.ThreadStart(f2));
y.Start();
y.Join(); // x線程等待y線程結束, 第二
Console.WriteLine("This is F1.{0}", 1);
}
static void f2()
{
Console.WriteLine("This is F2.{0}", 1); // y線程執行,第三
}
}
這兒有三個線程在處理(包括主線程),大家可看看執行結果.
結果:
This is Main.1
This is F2.1
This is F1.1
This is Main.2
如果: 注釋// x.Join();
結果:
This is Main.1
This is Main.2
This is F2.1
This is F1.1
另外:大家可以看看以下幾個方法的區別,有興趣的朋友可以用上面的例子進行測試
Thread.Suspend():掛起線程,或者如果線程已掛起,則不起作用;
Thread.Resume():繼續已掛起的線程;
Thread.Interrupt():中止處於 Wait或者Sleep或者Join 線程狀態的線程;
Thread.Sleep():將當前線程阻塞指定的毫秒數;
name:平平
mail:xzp91032@163.com