對於線程操作,一直沒有特別的會用。自己寫了些代碼:貼出來大家分享。
代碼
#region 簡單線程,主線程與子線程threadAnther,局部變數互不影響
static void SilmpleMultThread()
{
Thread threadAnther = new Thread(new ThreadStart(WrietConsole));
threadAnther.Start();//新線程啟動,
while (true) Console.Write("Y");//主線程不停的寫 “Y”
}
static void WrietConsole()
{
while(true) Console.Write("X");//不停的寫“X”
}
#endregion
#region 副本分別在各自的記憶體堆棧中建立
static void SimpleShareMultThread()
{
//變數x的副本分別在各自的記憶體堆棧中建立,輸出也一樣;
Thread threadAnther = new Thread(new ThreadStart(Go));
threadAnther.Start();
Go();
}
static void Go()
{
//聲明和使用同一個局部變數 x
for (int x = 0; x < 5; x++)
Console.Write("*");
}
#endregion
#region 多個線程引用了一些公用的目標執行個體的時候,他們共用資料
static void SimpleShareMuliThead()
{
//兩個線程都調用OutPut方法,他們共用done欄位。輸出結果是一個Done
Program prgoram = new Program();
prgoram.OutPut();
Thread threadAnother = new Thread(new ThreadStart(prgoram.OutPut));
threadAnother.Start();
}
bool done;
public void OutPut()
{
if (!done) { done = true; Console.Write("Done"); }
}
#endregion
#region 靜態欄位提供了另一種線程之間的共用資料
static bool outDone; //靜態欄位,為所有線程共用
static object locker = new object();
static void SimpleShareStaticMulThead()
{
Thread threadAnother = new Thread(OutDoneFunction);//線程初始化的另一種方法
threadAnother.Start();
OutDoneFunction();
}
static void OutDoneFunction()
{
//if (!outDone) { Console.Write("Done"); outDone = true; } //這種情況列印出兩個“Done”
lock (locker)
{
if (!outDone) { Console.Write("Done"); outDone = true; }
}//為了避免這種情況,用lock,鎖機制,確定同一時刻只有一個線程進入臨界區
// if (!outDone) { outDone = true; Console.Write("Done"); } //這種情況列印出一個“Done”
}
#endregion