First, use the singleton mode in the design mode to prevent multiple initialization of objects, causing inconsistency in access space.
A lock should be added at the counting point to temporarily block other thread counting to ensure the accuracy of the counting.
If you want to count and output in real time, you can lock the counting and output together. Otherwise, the counting and output results of different threads may not be processed in order.
Locking in this way can ensure sequential processing and sequential output, but this will somewhat lose some performance.
The lock position in the code is very important
This program will add three operations. The reason is that this thread has not reached 200 times, but there must be a thread added for the first time, so make a judgment in add.
Copy the code code as follows:
CommonSigleton MyCounter =CommonSigleton.Instance;
/// <summary>
/// Thread work
/// </summary>
public void DoSomeWork()
{
///Construct display string
string results = "";
///Create a Sigleton instance
System.Threading.Thread.Sleep(100);
int i = 0;
while (MyCounter.GetCounter() < 200)
{
// Ensure that the count is consistent with the output. Even if a time interval is added between the count and the output, this area will be locked to prevent other threads from operating.
lock(this)
{
///Start counting
MyCounter.Add();
System.Threading.Thread.Sleep(100);
Thread thread = Thread.CurrentThread;
results += "thread";
results += i++.ToString() + "――〉" + thread.Name + " ";
results += "Current count:";
results += MyCounter.GetCounter().ToString();
results += "/n";
Console.WriteLine(results);
// Clear the display string
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();
///Thread 0 only performs the same work as other threads
DoSomeWork();
}
}