C # multi-thread race instance

Source: Internet
Author: User

Combined with the previous article "multi-thread basics", this time we write a multi-thread race instance, the content is very simple: Superman and spider race, because Superman flies faster than spider, in order to be fair, we asked Spider to run a little longer, and the referee was responsible for announcing the start and end of the game.

Class multithread {// define two threads: Superman and spider Private Static thread Superman; Private Static thread Spiderman; // program entry. Static void main (string [] ARGs) starts the competition) {// initialize data initdata (); // The referee starts to race judgework ();} /// <summary> /// initialize the thread and name of Superman and spider // </Summary> Private Static void initdata () {Superman = new thread (New parameterizedthreadstart (runnerwork); Spiderman = new thread (New parameterizedthreadstart (runne Rwork); Superman. name = "Superman"; Spiderman. name = "Spiderman" ;}/// <summary> // The referee starts the competition and finally announces the winner. /// </Summary> Private Static void judgework () {console. writeline ("{0} PK {1}", Superman. name, Spiderman. name); console. writeline ("the competition is about to begin. Please be prepared! "); Console. writeline (" ready! "); Console. Read (); // Superman starts running console. writeline (" press enter to start running! "); Console. Beep (654,120 0); Superman. Start (500); // monster starts to run console. writeline (" press enter and the Spiderman starts to run! "); Spiderman. start (200); Superman. join (); Spiderman. join (); // announce the Race Result console. writeline ("I am announcing the game is over"); // The program suspends the thread for 12 seconds. sleep (12000 );} /// <summary> /// race process /// </Summary> /// <Param name = "OBJ"> race parameter </param> Private Static void runnerwork (Object OBJ) {int length = int32.parse (obj. tostring (); thread currentthread = thread. currentthread; string curthreadname = currentthread. name; int speed; // The Superman speed is 2 0 if (curthreadname = Superman. name) {speed = 50;} // The speed of spider is 20 else if (curthreadname = Spiderman. name) {speed = 20;} // If the thread is not controlled, use the following speed else {speed = 1;} console. writeline ("{0}, start ............ ", Curthreadname); For (int count = speed; count <= length; count + = speed) {thread. Sleep (1000); console. writeline (" {0 }...... Ran to the {1} meter ", curthreadname, Count. tostring ();} console. writeline (" {0}, reached the end! Welcome ...... ", Curthreadname );}}

Running result:


At the beginning of the competition, the referee declared the conclusion, which is not in common sense. After careful analysis, we can find that there are three processes that can be controlled by the program, namely the referee, Superman, and spider. The three processes are independent of each other at the same time, therefore, after the referee announces the start of the game, the referee will continue to announce the end of the game according to its thread.
We can: After the referee announces the start of the competition, let Spider-Man and Superman execute the thread and then execute the referee process:

// Prevent the referee's main process from being completed first, so that the processes of Superman and spider are executed first. join (); Spiderman. join (); console. writeline ("I announce the end of the Competition ");

The result of this execution is:


When the race was over, the referee declared that the competition was over. But there is still a problem. The referee had to announce who had won the competition. Why are there so many fans waiting? In this case, we can save the signature as a variable to announce who is the champion.
To demonstrate synchronous asynchronous read/write, let Superman race to save the world, and then come back to continue the competition; the first person to reach the end, spend his time looking for chalk, and then sign on the blackboard, when others see a name on the blackboard, they cannot write it any more. The referee announces that the name is the winner.

Class multithread3 {// The blackboard static string nameboard = "" for signature; // defines two threads: Superman and Spider-Man Private Static thread Superman; Private Static thread Spiderman; // program entry, static void main (string [] ARGs) starting the competition {// initialize the data initdata (); // The referee starts the race judgework ();} /// <summary> /// initialize the thread and name of Superman and spider // </Summary> Private Static void initdata () {Superman = new thread (New parameterizedthreadstart (runnerwork); Spiderman = new th Read (New parameterizedthreadstart (runnerwork); Superman. name = "Superman"; Spiderman. name = "Spiderman" ;}/// <summary> // The referee starts the competition and finally announces the winner. /// </Summary> Private Static void judgework () {console. writeline ("{0} PK {1}", Superman. name, Spiderman. name); console. writeline ("the competition is about to begin. Please be prepared! "); Console. writeline (" ready! "); Console. Read (); // Superman starts running console. writeline (" press enter to start running! "); Console. Beep (654,120 0); Superman. Start (500); // monster starts to run console. writeline (" press enter and the Spiderman starts to run! "); Spiderman. start (300); // prevent the referee's main process from being terminated first, so that the processes of Superman and spider can be executed first. join (); Spiderman. join (); // announce the Race Result announcewinner (); // The program suspends the thread for 12 seconds. sleep (12000 );} /// <summary> /// race process /// </Summary> /// <Param name = "OBJ"> race parameter </param> Private Static void runnerwork (Object OBJ) {int length = int32.parse (obj. tostring (); thread currentthread = thread. currentthread; string curthreadname = currentthread. name; I NT speed; // The Superman speed is 20 if (curthreadname = Superman. name) {speed = 50;} // The speed of spider is 20 else if (curthreadname = Spiderman. name) {speed = 20;} // If the thread is not controlled, use the following speed else {speed = 1;} console. writeline ("{0}, start ............ ", Curthreadname); For (int count = speed; count <= length; count + = speed) {thread. Sleep (1000); console. writeline (" {0 }...... Ran to meter {1} ", curthreadname, Count. tostring (); // If (COUNT = length/2) {If (curthreadname = Superman. name) {console. writeline ("The end of the world is coming, Superman is saving the world ...... "); String waitinfo = ".. "; // the process of saving the world for Superman (Int J = 0; j <= 10; j ++) {console. writeline ("Superman saving the world" + waitinfo); waitinfo + = ".. "; thread. sleep (1000);} console. writeline ...... ") ;}} Console. writeline (" {0}, to the end! Welcome ...... ", Curthreadname); writename (curthreadname) ;}/// <summary> /// after the key line is reached, the contestant signs the name on the blackboard /// </Summary> /// <Param name = "name"> contestant name </param> Private Static void writename (string name) {// If (nameboard. length = 0) {console. writeline ("{0} found chalk ...... ", Name); // the time it took to find the chalk thread. Sleep (9000); console. writeline (" {0} came back with the chalk and started signing ...... ", Name); nameboard = Name; console. writeline (" {0} after the end of the domain name, happy to leave ...... ", Name) ;}// when there is a signature on the blackboard, you cannot sign else {console. writeline (" {0} found that it has been signed, sang Xin left ...... ", Name) ;}/// <summary> // announce the competition result /// </Summary> Private Static void announcewinner () {console. writeline ("I am the referee, I announce that the winner of this competition is {0}", nameboard );}}

Running result:



It can be seen that when Superman is still saving the Earth, Spiderman has reached the final point, while the champion announced by the referee is Superman. After carefully analyzing the program, you can know that, although Spiderman first reaches the end and finds that the blackboard is empty, Superman reaches the end when Spiderman looks for chalk, they also found that the blackboard was empty, so they both wrote their own names, but because the latter would cover the former, the winner became a superman, as shown in the process:


The cause of the problem is that after Spiderman arrives, Superman still sees the blackboard, that is, the blackboard is writable for two people, and the latter will overwrite the content of the former. This method is asynchronous writing.
How can we overcome this problem? You can use lock to lock the critical section Code as follows:

// Define an object-type objlock private static object objlock = new object (); /// <summary> /// after the key line is reached, the contestant signs the name on the blackboard /// </Summary> /// <Param name = "name"> contestant name </param> Private Static void writename (string name) {// asynchronous reading is used to filter out the threads that have already seen the signature and improve the efficiency. // If (nameboard. length = 0) {// because the above is asynchronous read, multiple threads may be able to enter this step lock (objlock) {// synchronous read mode if (nameboard. length = 0) {console. writeline ("{0} found chalk ...... ", Name); // the time it took to find the chalk thread. Sleep (9000); console. writeline (" {0} came back with the chalk and started signing ...... ", Name); nameboard = Name; console. writeline (" {0} after the end of the domain name, happy to leave ...... ", Name) ;}// when there is a signature on the blackboard, you cannot sign else {console. writeline (" {0}. The signature is found to have been deleted ...... ", Name );}}}}

It should be noted that the locked content (non-critical code) must be shared-type reference data, because it is of little significance to other threads if a local variable is not locked for a thread; the reference data type can ensure that the lock content of each thread points to the same address.

For intuitive display, there is no abstraction of Superman, spider, and referee classes. The above is a simple multi-threaded application instance. Of course, this is the tip of the iceberg of multithreading, more will be implemented in future development. This time, we strive to use multiple threads in the examination system to optimize question extraction and scoring functions.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.