The single piece mode in design mode is used first to prevent multiple initialization of objects, resulting in inconsistent access space.
 
Count to lock, the other thread count temporarily blocked to ensure the correctness of the count.
 
If you want to count real-time output in real time, you can lock the count and output at the same time, otherwise the count and output of different threads may not be processed sequentially.
 
This lock ensures sequential output, but it loses some performance
 
Lock location in code is important
 
This program adds three operations because this thread is less than 200 times, but there is bound to be a thread that increases for the first time so make a judgment in add
 
 
 
  
  Copy 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)
{
Guarantees that the count is consistent with the output, even if the time interval between the count and the output will lock the area, preventing other threads from operating
Lock (This)
{
Start Count
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);
  
 
 Empty 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 also only performs the same work as other threads
Dosomework ();
}
}