多線程計數,怎樣堅持計數精確的辦法。本站提示廣大學習愛好者:(多線程計數,怎樣堅持計數精確的辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是多線程計數,怎樣堅持計數精確的辦法正文
起首應用設計形式中的單件形式,避免屢次初始化對象,形成拜訪空間的紛歧致。
計數處要加lock,將其他線程計數臨時壅塞,包管計數的准確性。
假如要想及時計數及時輸入,可以將計數和輸入處一並lock處置,否則分歧線程的計數和輸入成果未必按次序處置,
如斯加鎖能包管按次序處置按次序輸入,不外如許若干都 喪失了一些機能
代碼中加鎖地位很主要
此法式會增長三次運算,緣由是本線程未到200次,然則必定會有一個線程第一次增長所以在add裡再做斷定
CommonSigleton MyCounter =CommonSigleton.Instance;
/// <summary>
/// 線程任務
/// </summary>
public void DoSomeWork()
{
///結構顯示字符串
string results = "";
///創立一個Sigleton實例
System.Threading.Thread.Sleep(100);
int i = 0;
while (MyCounter.GetCounter() < 200)
{
//包管計數與輸入分歧,即使計數與輸入之間加上時光距離也會為這塊區域加鎖,避免其他線程操作
lock (this)
{
///開端計數
MyCounter.Add();
System.Threading.Thread.Sleep(100);
Thread thread = Thread.CurrentThread;
results += "線程";
results += i++.ToString() + "——〉" + thread.Name + " ";
results += "以後的計數:";
results += MyCounter.GetCounter().ToString();
results += "\n";
Console.WriteLine(results);
// 清空顯示字符串
results = "";
}
}
}
public void StartMain()
{
Thread thread0 = Thread.CurrentThread;
thread0.Name = "Thread 0";
Thread thread1 =new Thread(new ThreadStart(DoSomeWork));
thread1.Name = "Thread 1";
Thread thread2 =new Thread(new ThreadStart(DoSomeWork));
thread2.Name = "Thread 2";
Thread thread3 =new Thread(new ThreadStart(DoSomeWork));
thread3.Name = "Thread 3";
thread1.Start();
thread2.Start();
thread3.Start();
///線程0也只履行和其他線程雷同的任務
DoSomeWork();
}
}