以前一直沒有在程序中寫過總結,再翻開程序時卻不知所雲,所以我決定寫總結
一般 一個應用程序就對應一個進程,一個進程可有一個或多個線程,而一般有一個主線程。
一般 一個應用程序就對應一個進程,一個進程可有一個或多個線程,而一般有一個主線程。
有的博客上說“至少一個主線程”,這一說法持有懷疑
主線程與子線程之間的關系
**默認情況,在新開啟一個子線程的時候,他是前台線程,只有,將線程的IsBackground屬性設為true;他才是后台線程
*當子線程是前台線程,則主線程結束並不影響其他線程的執行,只有所有前台線程都結束,程序結束
*當子線程是后台線程,則主線程的結束,會導致子線程的強迫結束
(個人理解,這樣設計的原因:因為后台線程一般做的都是需要花費大量時間的工作,如果不這樣設計,主線程已經結束,而后台工作線程還在繼續,第一有可能使程序陷入死循環,第二主線程已經結束,后台線程即時執行完成也已經沒有什么實際的意義)
實例代碼:
主線程與子線程之間的關系
**默認情況,在新開啟一個子線程的時候,他是前台線程,只有,將線程的IsBackground屬性設為true;他才是后台線程
*當子線程是前台線程,則主線程結束並不影響其他線程的執行,只有所有前台線程都結束,程序結束
*當子線程是后台線程,則主線程的結束,會導致子線程的強迫結束
(個人理解,這樣設計的原因:因為后台線程一般做的都是需要花費大量時間的工作,如果不這樣設計,主線程已經結束,而后台工作線程還在繼續,第一有可能使程序陷入死循環,第二主線程已經結束,后台線程即時執行完成也已經沒有什么實際的意義)
實例代碼:
static Thread Mainthread; //靜態變量,用來獲取主線程
static void Main(string[] args)
{
Mainthread= Thread.CurrentThread;//獲取主線程
Test1();
}
static void Main(string[] args)
{
Mainthread= Thread.CurrentThread;//獲取主線程
Test1();
}
private static void Test1()
{
Console.WriteLine("在主進程中啟動一個線程!");
{
Console.WriteLine("在主進程中啟動一個線程!");
Thread firstChild = new Thread(new ParameterizedThreadStart(ThreadProc));//threadStart 是一個委托,代表一個類型的方法
firstChild.Name = "線程1";
firstChild.IsBackground = true;
firstChild.Start(firstChild.Name);//啟動線程
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表示應掛起此線程以使其他等待線程能夠執行
}
}
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表示應掛起此線程以使其他等待線程能夠執行
}
}