First, use the single-piece mode in the design mode to prevent multiple object initialization, resulting in inconsistent access space.
Lock should be added to the counter to temporarily block the counting of other threads to ensure the correctness of the counting.
If you want to count real-time output in real time, you can lock both the count and output. Otherwise, the count and output results of different threads may not be processed in order,
So locking can ensure that output is processed in order, but this results in a loss of performance.
It is important to lock the location in the code.
This program will add three operations, because this thread has not reached 200 times, but there must be a thread added for the first time, so I will make a judgment in add.
Download the source code to my resources.
CommonSigleton MyCounter = CommonSigleton. Instance ;////// Thread work ///Public void DoSomeWork () {// construct the display 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 the interval between the count and the output is added, this area is 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 executes the same work as other threads DoSomeWork ();}}