Thread.Join()方法的理解
????? 今天是第一次在C#中接觸Thread,自己研究了一下其中Thread.Join()這個方法,下面談談自己的理解。
?
? ? ? Thread.Join()在MSDN中的解釋很模糊:Blocks the calling thread until a thread terminates
有兩個主要問題:1.什么是the calling thread?
? ? ? ? ? ? ? ? ? ???? 2.什么是a thread?
?
? ? ?? 首先來看一下有關的概念: 我們執(zhí)行一個.exe文件實際上就是開啟了一個進程,同時開啟了至少一個線程,
但是真正干活的是線程,就好比一個Team有好幾個人,但是真正干活的是人不是Team.
????? 具體到代碼來說,以Console Application為例:程序Test.exe從Main函數(shù)開始運行,實際上是有一個線程
在執(zhí)行Main函數(shù),我們稱作MainThread.假如我們在Main函數(shù)中聲明了一個Thread,稱作NewThread,并且調(diào)用了
NewThread.Start()的方法,那么 MainThread在處理Main函數(shù)里面的代碼時遇到NewThread.Start()時,就會
去調(diào)用NewThread.
? ? ?? 基于上面的討論,我們可以得出結論:在我們剛才的例子中the calling thread就是MainThread,而a thread
指的洽洽就是MainThread調(diào)用的NewThread線程。
?????? 現(xiàn)在回到MSDN的解釋,我們可以這么翻譯:當NewThread調(diào)用Join方法的時候,MainThread就被停止執(zhí)行,
直到NewThread線程執(zhí)行完畢 。 這樣就好理解了吧O(∩_∩)O哈哈~
?
? ? ?? 好了,前面分析完了,現(xiàn)在來看測試用例吧:
?
Titleusing System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Test
{
??? class TestThread
??? {
??????? private static void ThreadFuncOne()
??????? {
??????????? for (int i = 0; i < 10; i++)
??????????? {
??????????????? Console.WriteLine(Thread.CurrentThread.Name +"?? i =? " + i);
??????????? }
??????????? Console.WriteLine(Thread.CurrentThread.Name + " has finished");
??????? }
??????? static void Main(string[] args)
??????? {
??????????? Thread.CurrentThread.Name = "MainThread";
??????????? Thread newThread = new Thread(new ThreadStart(TestThread.ThreadFuncOne));
??????????? newThread.Name = "NewThread";
??????????? for (int j = 0; j < 20; j++)
??????????? {
??????????????? if (j == 10)
??????????????? {
??????????????????? newThread.Start();
??????????????????? newThread.Join();
??????????????? }
??????????????? else
??????????????? {
??????????????????? Console.WriteLine(Thread.CurrentThread.Name + "?? j =? " + j);
??????????????? }
??????????? }
??????????? Console.Read();
??????? }
??? }
}
總結
以上是生活随笔為你收集整理的Thread.Join()方法的理解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于CFS算法的schedule()源码
- 下一篇: 我的log4net使用手册(转自 htt