之前一直沒有在程序中寫過總結,再翻開程序時殊不知所云,因此我決定寫總結
通常 一個應用程序就對應一個進程,一個進程可有一個或多個線程,而通常有一個主線程。
有的博客上說「至少一個主線程」,這一說法持有懷疑
主線程與子線程之間的關係
**默認狀況,在新開啓一個子線程的時候,他是前臺線程,只有,將線程的IsBackground屬性設爲true;他纔是後臺線程
*當子線程是前臺線程,則主線程結束並不影響其餘線程的執行,只有全部前臺線程都結束,程序結束
*當子線程是後臺線程,則主線程的結束,會致使子線程的強迫結束
(我的理解,這樣設計的緣由:由於後臺線程通常作的都是須要花費大量時間的工做,若是不這樣設計,主線程已經結束,然後臺工做線程還在繼續,第一有可能使程序陷入死循環,第二主線程已經結束,後臺線程即時執行完成也已經沒有什麼實際的意義)
實例代碼:
static Thread Mainthread; //靜態變量,用來獲取主線程
static void Main(string[] args)
{
Mainthread= Thread.CurrentThread;//獲取主線程
Test1();
}
private static void Test1()
{
Console.WriteLine("在主進程中啓動一個線程!");
Thread firstChild = new Thread(new ParameterizedThreadStart(ThreadProc));//threadStart 是一個委託,表明一個類型的方法
firstChild.Name = "線程1";
firstChild.IsBackground = true;
firstChild.Start(firstChild.Name);//啓動線程
Thread secondChild = new Thread(new ParameterizedThreadStart(ThreadProc));
secondChild.Name = "線程2";
secondChild.IsBackground = true;
secondChild.Start(secondChild.Name);
Console.WriteLine("主線程結束");
Console.WriteLine(Mainthread.ThreadState);
Mainthread.Abort();
}
private static void ThreadProc(object str)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Mainthread.ThreadState);
Console.Write(str+"調用ThreadProc: " + i.ToString() + "\r\n");
if (i == 9)
Console.WriteLine(str + "結束");
Thread.Sleep(2000);//線程被阻塞的毫秒數。0表示應掛起此線程以使其餘等待線程可以執行
}
}