C # Multithreading Classic example eating apples

Source: Internet
Author: User
This article focuses on the classic examples of multithreaded development, which, through this example, can deepen the understanding of multithreading.

Example Overview:

Here is an example of how to implement multi-threading in C # by simulating an apple-eating instance. Requirements for the development of a program to achieve the following: A family has three children, mom and dad constantly peeling apples to the plate, the eldest, the second, old three constantly from the plate to eat apples. The size of the plate is limited, up to 5 apples, and mom and dad can not put apples on the plate at the same time, mother has priority. Three children when the apple, the plate can not be empty, three people can not be taken at the same time, old three priority, eldest brother lowest. Eldest brother Eat the fastest, take the highest frequency, the old two times.

Related to knowledge points:

Threads thread creates and controls a thread, sets its priority, and obtains its state.

Lock lock the most straightforward way to implement multi-threaded synchronization is to lock, which defines a piece of code as a mutex, allowing only one thread to go into execution at a time, while other threads must wait.

event EventHandler declares an event for the notification interface to make changes

Design ideas:

Productor represents the producer, used to peel apples.

Consumer says consumers are used to eating apples.

Dish plates, for apples, for middle class

EATAPPLESMP's Begineat () method, which means start eating apples, start the thread

-------------------------------------------------------------------------------------------------

The following "Mom and dad cut apples, children eat apples":

The background output is as follows:

Mama put 1 apples baba put 1 apples dage take apples to eat ... Erdi take apples to eat ... Sandi waiting to take Apple Mama put 1 apples sandi take apples to eat ... Baba put 1 apples dage take apples to eat ... Mama put 1 apples baba put 1 apples erdi take apples to eat ... Mama put 1 apples baba put 1 apples dage take apples to eat ... Sandi take apples to eat ... Mama put 1 apples baba put 1 apples erdi take apples to eat ... Mama put 1 apples baba put 1 apples dage take apples to eat ... Mama put 1 apples baba put 1 apples sandi take apples to eat ... Mama put 1 Apple Baba is waiting to put apple Erdi apples to eat ... Baba put 1 apples dage take apples to eat ... Mama put 1 Apple baba waiting to be put into Apple Mama is waiting to put Apple Sandi to take Apple to eat ... Baba put 1 apple Mama is waiting to put apple Erdi apples to eat ... Mama put 1 apples dage take apples to eat ... Baba put 1 apple Mama is waiting to put Apple dage apples to eat ... Mama put 1 Apple Baba is waiting to put apple Erdi apples to eat ... Baba put 1 apples sandi take apples to eat ... Mama put 1 Apple Baba is waiting to put Apple dage apples to eat ... Baba put 1 apple Mama is waiting to put apple Erdi apples to eat ... Mama put 1 Apple Baba is waiting to put apple Sandi apples to eat ... Baba put 1 apple Mama is waiting to put Apple dage apples to eat ... Mama put 1 Apple baba waiting to be put into Apple Mama is waiting to put Apple Erdi to take Apple to eat ... Mama put 1 Apple Baba is waiting to put Apple dage apples to eat ... Baba put 1 apple Mama is waiting to put apple Sandi apples to eat ... Mama put 1 Apple Baba is waiting to put Apple Mama is waiting to put Apple thread ' Mama ' (0X1CE0) has exited with a return value of 0 (0x0). Thread ' Baba ' (0x1888) has exited with a return value of 0 (0x0). Erdi take apples to eat ... Dage take apples to eat ... Sandi take apples to eat ... Dage take apples to eat ... Erdi take apples to eat ... Dage waiting to fetch apple Sandi wait for Apple Erdi wait for Apple

The Productor code is as follows:

  Using System;   Using System.Collections.Generic;   Using System.Linq;   Using System.Text;      Using System.Threading; namespace Demosharp.eatapple {//<summary>///producer//</summary> public class Produc          Tor {private Dish Dish;            private string name;              public string Name {get {return Name;}          set {name = value;}          Public EventHandler putaction;//declares an event when an apple is placed to trigger the event public Productor (string name, Dish Dish)              {this.name = name;          This.dish = dish; public void Run () {while (true) {bool flag= dish.                  Put (name); if (flag) {if (putaction! = null) {P                      Utaction (this, null);             } try {             Thread.Sleep (600);//Cut Apple Time} catch (Exception ex)                  {}} else {break; }              }          }      }  }

The

Consumer code is as follows:

  Using System;   Using System.Collections.Generic;    Using System.ComponentModel;    Using System.Data;    Using System.Drawing;    Using System.Linq;    Using System.Text;   Using System.Windows.Forms;   Using Demosharp.eatapple; namespace Demosharp {//<summary>///Page class///</summary> public partial class Eatapplefo           Rm:form {private EATAPPLESMP M_EATAPPLESMP = new EATAPPLESMP ();              Public Eatappleform () {InitializeComponent ();              Initview ();              M_eatapplesmp.putaction + = Putactionmethod;         M_eatapplesmp.getaction + = Getactionmethod;          }///<summary>//Initialize GroupBox//</summary> private void Initview ()              {this.gbBaba.Controls.Clear ();               This.gbMama.Controls.Clear ();              This.gbDage.Controls.Clear ();              This.gbErdi.Controls.Clear (); This.gbsandi.controls.cLear (); }///<summary>//Start thread///</summary>//<param name= "sender "></param>//<param name=" E "></param> private void btnStart_Click (object send              Er, EventArgs e) {this.m_EatAppleSmp.BeginEat (); }///<summary>//Apple Events///</summary>//<param NA Me= "Sender" ></param>//<param name= "E" ></param> private void Putactionmeth                  Od (object sender, EventArgs e) {Productor p = sender as Productor;                           if (P! = null) {if (P.name = = "Baba") {                        Additemtogroupbox (This.gbbaba, This.lblbaba);                     } if (p.name = = "Mama") {       Additemtogroupbox (This.gbmama, This.lblmama); }}}///<summary>//Apple Eating/ </summary>//<param name= "sender" ></param>//<param name= "E" >&l t;/param> public void Getactionmethod (object sender, EventArgs e) {Co                     Nsumer C = sender as Consumer;                               if (c! = null) {if (C.name = = "Dage") {                          Additemtogroupbox (This.gbdage, this.lbldage); } if (c.name = = "Erdi") {additemtogr                             Oupbox (This.gberdi, This.lblerdi);                         } if (c.name = = "Sandi") {          Additemtogroupbox (This.gbsandi, This.lblsandi);                      }}//<summary> Add objects to the specified GroupBox///</summary>//<param name= "GbV Iew "></param>//<param name=" LBL "></param> private Voi D additemtogroupbox (GroupBox Gbview,label lbl) {Gbview.invoke (new Acti                               On (() = {PictureBox p = new PictureBox ();                                P.width = 20;                               P.height = 20;                              P.dock = DockStyle.Left;                               P.image = This.imglst01.images[0];                               P.margin = new Padding (2); GBVIEW.CONTROLS.ADD (P);                                          })); Displays the number of LBL. Invoke (new Action () = {if (string. IsNullOrEmpty (LBL. Text) {lbl.  Text = "0";   Using System;   Using System.Collections.Generic;   Using System.Linq;   Using System.Text;     Using System.Threading;      namespace Demosharp.eatapple {//<summary>///Consumer//</summary> public class Consumer         {private string name;           public string Name {get {return Name;}        set {name = value;}          } private Dish Dish;         private int timelong;             Public EventHandler getaction;//declares an event when an apple is placed to trigger the event public Consumer (string name, Dish Dish, int timelong) {             THIS.name = name;             This.dish = dish;        This.timelong = Timelong; } public void Run ()        {while (true) {bool flag= dish.                Get (name);                   if (flag) {//if fetch to Apple, then call event and start eating if (getaction! = null)                    {getaction (this, null);                    try {thread.sleep (Timelong);//Eat Apple Time}                 catch (ThreadInterruptedException) {}}                  else {break; }}}}} lbl. Text = (int. Parse (LBL. Text) + 1).                            ToString ();                        })); }                     }                  }

The

Dish code is as follows:

 Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;    Using System.Threading;     namespace Demosharp.eatapple {//<summary>///plate, middle class///</summary> public class Dish {private int f = 5;//means a few apples can be placed on the plate, up to 5 apples private int enablednum;//The total number of apples private int n = 0;         Indicates how many apples have been put in private object objget = new Object ();          Private Object objput = new Object (); <summary>///constructor, initialize dish object///</summary>//<param name= "num" > indicates how many Apple knots are cut Bundle </param> Public Dish (Int. num) {this.         Enablednum = num; }///<summary>///For Apple///</summary>//<param name= "name" ></pa Ram>///<returns> whether to put success </returns> public bool put (string name) {Lock (th     IS)//sync control put Apple {bool flag = false; while (f = = 0//The Apple is full, the thread waits {try {System.Console.WriteLine (name + "is waiting to put the apple");       Monitor.Wait (this);    } catch (Exception ex) {System.Console.WriteLine (name + "Can't Wait"); }} if (n < enablednum) {f = f-1;//cut an apple and put it once n = n + 1;  System.Console.WriteLine (name + "Put 1 apples");      Flag = true;        } monitor.pulseall (this);      return flag; }}///<summary>///For Apple///</summary>//<param name= "name" ></p Aram> public bool Get (string name) {Lock (this)//synchronize control fetch Apple {BOOL flag = False               ; while (f = = 5) {try {System.Console.WriteLine (name                      + "Wait for Apple");                    Monitor.Wait (this);           } catch (ThreadInterruptedException) {}} if (n <= enablednum) {f = f + 1; System.Console.WriteLine (nAme + "take apples to eat ...");           Flag = true;            } monitor.pulseall (this);     return flag; }     }   } }

The

EATAPPLESMP code is as follows:

 Using System;  Using System.Collections.Generic;  Using System.Linq;  Using System.Text;    Using System.Threading; Namespace Demosharp.eatapple {public class EATAPPLESMP {public EventHandler putaction;//declares an event that is triggered when an apple is placed The event public EventHandler getaction;//declares an event that triggers the event when an apple is placed///<summary>///start eating Apple///< /summary> public void Begineat () {Thread th_mother, Th_father, Th_young, Th_middle, th_old;//             The second show mom, Dad, brother, two younger brother, eldest brother Dish Dish = new Dish (30); Productor mother = new Productor ("Mama", dish);//Create thread mother.             Putaction + = Putactionmethod;            Productor father = new Productor ("Baba", dish); Father.           Putaction + = Putactionmethod;             Consumer old = new Consumer ("Dage", Dish, 1200); Old.            Getaction + = Getactionmethod;            Consumer middle = new Consumer ("Erdi", Dish, 1500); Middle.            Getaction + = Getactionmethod; Consumer yOung = new Consumer ("Sandi", Dish, 1800); Young.             Getaction + = Getactionmethod;            Th_mother = new Thread (new ThreadStart (Mother.run)); Th_mother.            Name = "Mama";             Th_father = new Thread (new ThreadStart (Father.run)); Th_father.             Name = "Baba";             Th_old = new Thread (new ThreadStart (Old.run)); Th_old.             Name = "Dage";            Th_middle = new Thread (new ThreadStart (Middle.run)); Th_middle.            Name = "Erdi";            Th_young = new Thread (new ThreadStart (Young.run)); Th_young.             Name = "Sandi"; Th_mother. Priority = threadpriority.highest;//Sets the precedence th_father.            priority = Threadpriority.normal; Th_old.            priority = Threadpriority.lowest; Th_middle.            priority = Threadpriority.normal; Th_young.             priority = Threadpriority.highest; Th_mother.             Start (); Th_father.             Start (); Th_old.            Start (); Th_middle.            Start (); Th_yOung.         Start ();            private void Getactionmethod (Object Sender,eventargs e) {if (getaction! = null)             {getaction (sender, E);             }} private void Putactionmethod (object sender, EventArgs e) {if (putaction! = null)             {putaction (sender, E); }         }     }}

The

Interface class code is as follows:

  Using System;   Using System.Collections.Generic;    Using System.ComponentModel;    Using System.Data;    Using System.Drawing;    Using System.Linq;    Using System.Text;   Using System.Windows.Forms;   Using Demosharp.eatapple; namespace Demosharp {//<summary>///Page class///</summary> public partial class Eatapplefo           Rm:form {private EATAPPLESMP M_EATAPPLESMP = new EATAPPLESMP ();              Public Eatappleform () {InitializeComponent ();              Initview ();              M_eatapplesmp.putaction + = Putactionmethod;         M_eatapplesmp.getaction + = Getactionmethod;          }///<summary>//Initialize GroupBox//</summary> private void Initview ()              {this.gbBaba.Controls.Clear ();               This.gbMama.Controls.Clear ();              This.gbDage.Controls.Clear ();              This.gbErdi.Controls.Clear (); This.gbsandi.controls.cLear (); }///<summary>//Start thread///</summary>//<param name= "sender "></param>//<param name=" E "></param> private void btnStart_Click (object send              Er, EventArgs e) {this.m_EatAppleSmp.BeginEat (); }///<summary>//Apple Events///</summary>//<param NA Me= "Sender" ></param>//<param name= "E" ></param> private void Putactionmeth                  Od (object sender, EventArgs e) {Productor p = sender as Productor;                           if (P! = null) {if (P.name = = "Baba") {                        Additemtogroupbox (This.gbbaba, This.lblbaba);                     } if (p.name = = "Mama") {       Additemtogroupbox (This.gbmama, This.lblmama); }}}///<summary>//Apple Eating/ </summary>//<param name= "sender" ></param>//<param name= "E" >&l t;/param> public void Getactionmethod (object sender, EventArgs e) {Co                     Nsumer C = sender as Consumer;                               if (c! = null) {if (C.name = = "Dage") {                          Additemtogroupbox (This.gbdage, this.lbldage); } if (c.name = = "Erdi") {additemtogr                             Oupbox (This.gberdi, This.lblerdi);                         } if (c.name = = "Sandi") {          Additemtogroupbox (This.gbsandi, This.lblsandi);                      }}//<summary> Add objects to the specified GroupBox///</summary>//<param name= "GbV Iew "></param>//<param name=" LBL "></param> private Voi D additemtogroupbox (GroupBox Gbview,label lbl) {Gbview.invoke (new Acti                               On (() = {PictureBox p = new PictureBox ();                                P.width = 20;                               P.height = 20;                              P.dock = DockStyle.Left;                               P.image = This.imglst01.images[0];                               P.margin = new Padding (2); GBVIEW.CONTROLS.ADD (P);                                          })); Displays the number of LBL. Invoke (new Action () = {if (string. IsNullOrEmpty (LBL. Text) {lbl.                                Text = "0"; } lbl. Text = (int. Parse (LBL. Text) + 1).                            ToString ();                        })); }                     }                  }
Related Article

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.