C# 多线程经典示例 吃苹果

本文主要讲述了多线程开发中经典示例,通过本示例,可以加深对多线程的理解。

示例概述:

  下面用一个模拟吃苹果的实例,说明C#中多线程的实现方法。要求开发一个程序实现如下情况:一个家庭有三个孩子,爸爸妈妈不断削苹果往盘子里面放,老大、老二、老三不断从盘子里面取苹果吃。盘子的大小有限,最多只能放5个苹果,并且爸妈不能同时往盘子里面放苹果,妈妈具有优先权。三个孩子取苹果时,盘子不能为空,三人不能同时取,老三优先权最高,老大最低。老大吃的最快,取的频率最高,老二次之。

 

涉及到知识点:

线程Thread 创建并控制线程,设置其优先级并获取其状态。

锁 lock 用于实现多线程同步的最直接办法就是加锁,它可以把一段代码定义为互斥段,在一个时刻内只允许一个线程进入执行,而其他线程必须等待。

事件EventHandler 声明一个事件,用于通知界面做改变

设计思路:

Productor 表示生产者,用于削苹果。

Consumer 表示消费者,用于吃苹果。

Dish 盘子,用于装苹果,做为中间类

EatAppleSmp 的BeginEat()方法,表示开始吃苹果,启动线程

 ————————————————————————————————-

效果图如下【爸爸妈妈削苹果,孩子吃苹果】:

C# 多线程经典示例 吃苹果

后台输出如下:

Mama放1个苹果Baba放1个苹果Dage取苹果吃...Erdi取苹果吃...Sandi等待取苹果Mama放1个苹果Sandi取苹果吃...Baba放1个苹果Dage取苹果吃...Mama放1个苹果Baba放1个苹果Erdi取苹果吃...Mama放1个苹果Baba放1个苹果Dage取苹果吃...Sandi取苹果吃...Mama放1个苹果Baba放1个苹果Erdi取苹果吃...Mama放1个苹果Baba放1个苹果Dage取苹果吃...Mama放1个苹果Baba放1个苹果Sandi取苹果吃...Mama放1个苹果Baba正在等待放入苹果Erdi取苹果吃...Baba放1个苹果Dage取苹果吃...Mama放1个苹果Baba正在等待放入苹果Mama正在等待放入苹果Sandi取苹果吃...Baba放1个苹果Mama正在等待放入苹果Erdi取苹果吃...Mama放1个苹果Dage取苹果吃...Baba放1个苹果Mama正在等待放入苹果Dage取苹果吃...Mama放1个苹果Baba正在等待放入苹果Erdi取苹果吃...Baba放1个苹果Sandi取苹果吃...Mama放1个苹果Baba正在等待放入苹果Dage取苹果吃...Baba放1个苹果Mama正在等待放入苹果Erdi取苹果吃...Mama放1个苹果Baba正在等待放入苹果Sandi取苹果吃...Baba放1个苹果Mama正在等待放入苹果Dage取苹果吃...Mama放1个苹果Baba正在等待放入苹果Mama正在等待放入苹果Erdi取苹果吃...Mama放1个苹果Baba正在等待放入苹果Dage取苹果吃...Baba放1个苹果Mama正在等待放入苹果Sandi取苹果吃...Mama放1个苹果Baba正在等待放入苹果Mama正在等待放入苹果线程 'Mama' (0x1ce0) 已退出,返回值为 0 (0x0)。线程 'Baba' (0x1888) 已退出,返回值为 0 (0x0)。Erdi取苹果吃...Dage取苹果吃...Sandi取苹果吃...Dage取苹果吃...Erdi取苹果吃...Dage等待取苹果Sandi等待取苹果Erdi等待取苹果

Productor 代码如下:

  using System;   using System.Collections.Generic;   using System.Linq;   using System.Text;   using System.Threading;      namespace DemoSharp.EatApple   {       ///       /// 生产者      ///       public class Productor      {          private Dish dish;          private string name;            public string Name          {              get { return name; }              set { name = value; }          }            public EventHandler PutAction;//声明一个事件,当放苹果时触发该事件           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)                      {                          PutAction(this, null);                      }                      try                      {                          Thread.Sleep(600);//削苹果时间                      }                      catch (Exception ex)                      {                       }                  }                  else {                      break;                  }              }          }      }  }

Consumer代码如下:

  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  {      ///       /// 页面类     ///       public partial class EatAppleForm : Form      {         private EatAppleSmp m_EatAppleSmp = new EatAppleSmp();           public EatAppleForm()         {             InitializeComponent();              InitView();              m_EatAppleSmp.PutAction += PutActionMethod;              m_EatAppleSmp.GetAction += GetActionMethod;         }           ///          /// 初始化GroupBox          ///           private void InitView()          {              this.gbBaba.Controls.Clear();              this.gbMama.Controls.Clear();               this.gbDage.Controls.Clear();              this.gbErdi.Controls.Clear();              this.gbSandi.Controls.Clear();         }            ///           /// 启动线程            ///               ///             ///             private void btnStart_Click(object sender, EventArgs e)             {                 this.m_EatAppleSmp.BeginEat();              }                  ///              /// 放苹果事件             ///              ///              ///               private void PutActionMethod(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);                        }                  }                }                        ///                 /// 吃苹果事件                ///               ///                 ///                 public void GetActionMethod(object sender, EventArgs e)                {                    Consumer c = sender as Consumer;                     if (c != null)                     {                          if (c.Name == "Dage")                         {                               AddItemToGroupBox(this.gbDage, this.lblDage);                          }                           if (c.Name == "Erdi")                              {                               AddItemToGroupBox(this.gbErdi, this.lblErdi);                             }                              if (c.Name == "Sandi")                                {                                   AddItemToGroupBox(this.gbSandi, this.lblSandi);                              }                            }                       }                                       ///                       /// 往指定的GroupBox中添加对象                      ///                         ///                         ///                        private void AddItemToGroupBox(GroupBox gbView,Label lbl)                       {                              gbView.Invoke(new Action(() =>                            {                                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);                                           }));                             //显示个数                            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  {      ///      /// 消费者        ///      public class Consumer     {          private string name;         public string Name        {            get { return name; }           set { name = value; }        }        private Dish dish;          private int timelong;         public EventHandler GetAction;//声明一个事件,当放苹果时触发该事件       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 (GetAction != null)                   {                        GetAction(this, null);                    }                     try                    {                        Thread.Sleep(timelong);//吃苹果时间                    }                    catch (ThreadInterruptedException)                     {                     }                }                 else {                      break;                  }            }        }     } }                                }                                lbl.Text = (int.Parse(lbl.Text) + 1).ToString();                            }));                        }                     }                  }

Dish代码如下:

 using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using System.Threading;    namespace DemoSharp.EatApple  {      ///      /// 盘子,属于中间类     ///      public class Dish     {         private int f = 5;//表示盘子中还可以放几个苹果,最多只能放5个苹果          private int EnabledNum;//可放苹果总数         private int n = 0; //表示已经放了多少个苹果          private object objGet = new object();         private object objPut = new object();          ///          /// 构造函数,初始化Dish对象         ///          /// 表示削够多少个苹果结束         public Dish(int num)         {             this.EnabledNum = num;         }         ///          /// 放苹果的方法         ///          ///           ///是否放成功         public bool Put(string name)        {            lock (this)//同步控制放苹果   {   bool flag = false;     while (f == 0)//苹果已满,线程等待    {      try         {         System.Console.WriteLine(name + "正在等待放入苹果");          Monitor.Wait(this);       }       catch (Exception ex) {    System.Console.WriteLine(name + "等不及了");    }  }   if (n < EnabledNum)  {   f = f - 1;//削完一个苹果放一次     n = n + 1; System.Console.WriteLine(name + "放1个苹果");  flag = true;      }  Monitor.PulseAll(this);        return flag;      }      }       ///        /// 取苹果的方法        ///         ///        public bool Get(string name)       {         lock (this)//同步控制取苹果           {             bool flag = false;               while (f == 5)              {                  try                  {                       System.Console.WriteLine(name + "等待取苹果");                      Monitor.Wait(this);                    }                    catch (ThreadInterruptedException) { }   }      if (n <= EnabledNum)      {             f = f + 1;          System.Console.WriteLine(name + "取苹果吃...");             flag = true;           }              Monitor.PulseAll(this);            return flag;     }     }   } }

EatAppleSmp代码如下:

 using System;  using System.Collections.Generic;  using System.Linq;  using System.Text;  using System.Threading;    namespace DemoSharp.EatApple  {      public class EatAppleSmp     {         public EventHandler PutAction;//声明一个事件,当放苹果时触发该事件        public EventHandler GetAction;//声明一个事件,当放苹果时触发该事件         ///          /// 开始吃苹果        ///          public void BeginEat()        {          Thread th_mother, th_father, th_young, th_middle, th_old;//依次表示妈妈,爸爸,小弟,二弟,大哥             Dish dish = new Dish(30);             Productor mother = new Productor("Mama", dish);//建立线程             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;//设置优先级             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);             }         }     }}

界面类代码如下:

  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  {      ///       /// 页面类     ///       public partial class EatAppleForm : Form      {         private EatAppleSmp m_EatAppleSmp = new EatAppleSmp();           public EatAppleForm()         {             InitializeComponent();              InitView();              m_EatAppleSmp.PutAction += PutActionMethod;              m_EatAppleSmp.GetAction += GetActionMethod;         }           ///          /// 初始化GroupBox          ///           private void InitView()          {              this.gbBaba.Controls.Clear();              this.gbMama.Controls.Clear();               this.gbDage.Controls.Clear();              this.gbErdi.Controls.Clear();              this.gbSandi.Controls.Clear();         }            ///           /// 启动线程            ///               ///             ///             private void btnStart_Click(object sender, EventArgs e)             {                 this.m_EatAppleSmp.BeginEat();              }                  ///              /// 放苹果事件             ///              ///              ///               private void PutActionMethod(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);                        }                  }                }                        ///                 /// 吃苹果事件                ///               ///                 ///                 public void GetActionMethod(object sender, EventArgs e)                {                    Consumer c = sender as Consumer;                     if (c != null)                     {                          if (c.Name == "Dage")                         {                               AddItemToGroupBox(this.gbDage, this.lblDage);                          }                           if (c.Name == "Erdi")                              {                               AddItemToGroupBox(this.gbErdi, this.lblErdi);                             }                              if (c.Name == "Sandi")                                {                                   AddItemToGroupBox(this.gbSandi, this.lblSandi);                              }                            }                       }                                       ///                       /// 往指定的GroupBox中添加对象                      ///                         ///                         ///                        private void AddItemToGroupBox(GroupBox gbView,Label lbl)                       {                              gbView.Invoke(new Action(() =>                            {                                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);                                           }));                             //显示个数                            lbl.Invoke(new Action(() => {                               if (string.IsNullOrEmpty(lbl.Text))                                 {                                     lbl.Text = "0";                                }                                lbl.Text = (int.Parse(lbl.Text) + 1).ToString();                            }));                        }                     }                  }

更多C# 多线程经典示例 吃苹果相关文章请关注PHP中文网!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1432154.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
C#希尔排序
上一篇 2025年12月17日 06:16:46
下一篇 2025年12月17日 06:16:59

相关推荐

  • c++中的SFINAE技术是什么_c++模板编程中的SFINAE原理与应用

    SFINAE 是“替换失败不是错误”的原则,指模板实例化时若参数替换导致错误,只要存在其他合法候选,编译器不报错而是继续重载决议。它用于条件启用模板、类型检测等场景,如通过 decltype 或 enable_if 控制函数重载,实现类型特征判断。尽管 C++20 引入 Concepts 简化了部分…

    2026年5月10日
    000
  • c#文件怎么打开

    打开 C# 文件有三种方法:Visual Studio:启动 Visual Studio,通过“文件”菜单打开 C# 文件。文本编辑器:使用文本编辑器打开 C# 文件,将其视为普通文本。.NET Core 命令行工具:使用 csc.exe 命令行工具编译 C# 文件,生成可执行文件。 如何打开 C#…

    2026年5月10日
    000
  • c++如何实现UDP通信_c++基于UDP的网络通信示例

    UDP通信基于套接字实现,适用于实时性要求高的场景。1. 流程包括创建套接字、绑定地址(接收方)、发送(sendto)与接收(recvfrom)数据、关闭套接字;2. 服务端监听指定端口,接收客户端消息并回传;3. 客户端发送消息至服务端并接收响应;4. 跨平台需处理Winsock初始化与库链接,编…

    2026年5月10日
    100
  • 函数指针在 C++ 多态中的作用:揭示多态背后的真相

    函数指针在 C++ 多态中的作用:揭示多态背后的真相 简介 多态是面向对象编程的一项强大功能,它允许对象在运行时以不同的方式表现。C++ 中的多态实现依赖于函数指针。本文将深入探讨函数指针在多态中的作用,并通过一个实战案例展示如何利用它们。 函数指针 立即学习“C++免费学习笔记(深入)”; 函数指…

    2026年5月10日
    000
  • C++框架与Java框架在易用性方面的比较

    c++++ 框架的易用性低于 java 框架,具体原因如下:c++ 框架学习曲线陡峭,需要深入理解 c++ 语言。易出错且调试困难。而 java 框架具有以下易用性优势:学习曲线低,尤其适合 java 初学者。提供丰富的库和工具,简化开发。运行时异常处理,简化异常处理。 C++ 框架与 Java 框…

    2026年5月10日
    000
  • c++中头文件和源文件的区别_c++头文件与源文件作用对比

    头文件声明接口,源文件实现逻辑。头文件含类、函数声明及宏定义,通过#include被多文件共享,用include守卫防重;源文件实现具体功能,编译为目标文件后由链接器合并。声明与实现分离提升模块化与编译效率,模板和内联函数因需编译时可见故常置于头文件,命名空间避免符号冲突,整体结构使项目更清晰易维护…

    2026年5月10日
    000
  • C++ 函数重载在事件驱动的编程中的应用

    在事件驱动的编程中,函数重载可创建具有不同参数签名的相似功能,为单一函数名提供多样化功能。它包含以下优点:代码可读性:使用单一函数名表示相关任务。可维护性:避免重复编写类似逻辑。可重用性:跨项目和应用程序 reutilizar。 C++ 函数重载在事件驱动的编程中的应用 在事件驱动的编程中,函数重载…

    2026年5月10日
    000
  • C++ 函数性能优化对系统稳定性的影响

    标题:C++ 函数性能优化对系统稳定性的影响 简介 函数性能优化是 C++ 程序员提高程序效率的关键技术。本文将探讨函数性能优化对系统稳定性的影响,并提供实战案例来证明这一点。 性能优化对稳定性的作用 立即学习“C++免费学习笔记(深入)”; 函数性能优化不仅可以提升程序速度,还可以提高系统的稳定性…

    2026年5月10日
    000
  • WebAssembly中导入JavaScript函数:无胶水代码集成指南

    本文深入探讨了在WebAssembly模块中直接导入和使用JavaScript函数的机制,特别是当使用Emscripten的STANDALONE_WASM和SIDE_MODULE编译模式时。文章详细分析了TypeError: import object field ‘GOT.mem&#8…

    2026年5月10日
    000
  • C++如何编译和链接_C++从源码到可执行文件的过程解析

    c++kquote>预处理展开宏和头文件,编译生成汇编代码,汇编转为机器码,链接合并目标文件与库生成可执行程序。 当你写完一段C++代码,比如一个简单的hello world程序,最终能运行起来,背后其实经历了一系列步骤:预处理、编译、汇编和链接。这个过程将人类可读的源码转换成机器可以执行的程…

    2026年5月10日
    000
  • c++中sizeof运算符的用法和常见陷阱 _c++ sizeof使用技巧及陷阱解析

    sizeof运算符在编译时计算类型或对象的字节大小,返回size_t类型,常用于获取数据大小、数组元素个数及内存操作;但存在数组传参退化为指针导致失效、对指针无法获知动态内存大小、表达式不求值、结构体因对齐产生填充等常见陷阱;需结合模板、显式传参、对齐控制等方式规避问题,提升代码可移植性和安全性。 …

    2026年5月10日
    000
  • C#如何进行网络编程?Socket与TCP/IP通信编程实例详解

    C#通过Socket类实现TCP通信,首先服务器绑定IP和端口并监听,客户端发起连接,双方通过Send/Receive收发数据,最后关闭连接。 C# 进行网络编程主要依赖于 System.Net 和 System.Net.Sockets 命名空间,其中最核心的是使用 Socket 类实现基于 TCP…

    2026年5月10日
    000
  • C++ 函数递归详解:递归查找列表中的元素

    递归查找列表元素的步骤如下:递归基础条件:如果列表为空,则元素不存在。递归过程:使用递归调用查找列表的剩余部分,并调整返回的索引。检查列表的第一个元素:如果第一个元素与所查找的元素相等,则元素位于索引 0 处。找不到:如果递归和第一个元素检查都没有找到,则元素不存在。 C++ 函数递归详解:递归查找…

    2026年5月10日
    000
  • C++怎么使用C++17的并行算法库_C++ std::execution与多核性能优化

    c++kquote>C++17通过std::execution策略引入并行算法支持,需编译器(如GCC 8+)和线程库(如TBB)配合;提供seq、par、par_unseq三种策略控制执行模式;可用于sort、for_each等算法提升大数据性能,但需避免数据竞争,推荐使用reduce等安全…

    2026年5月10日
    000
  • c++ lambda表达式怎么写 c++匿名函数用法详解

    答案是lambda表达式可简洁定义匿名函数,用于STL算法等场景。其语法包含捕获列表、参数列表、mutable、返回类型和函数体,如[=](int x) { return x > 0; }可值捕获外部变量并用于判断正数。 在C++中,lambda表达式是一种创建匿名函数的简洁方式,常用于需要传…

    2026年5月10日
    200
  • C++框架的Unlicense许可类型简介

    unlicense 许可证类型为免费且宽松,允许用户在不附加任何限制的情况下使用、修改和分发软件。它旨在最大限度地减少限制和允许最大的自由度,具有以下好处:简洁易懂高度开放无保证 C++ 框架的 Unlicense 许可证类型简介 了解 Unlicense Unlicense 是一个自由和宽松的软件…

    2026年5月10日
    000
  • 利用日志记录增强 C++ 函数的调试能力

    如何利用日志记录增强 c++++ 函数的调试能力?使用 glog 库进行日志记录: 安装 glog,并在代码中使用 glog 头文件和 initgooglelogging() 初始化日志记录。添加日志记录语句: 使用 log() 宏在要记录的代码块中添加日志记录语句,以记录函数开始、结束或其他重要事…

    2026年5月10日
    000
  • C++ 函数模板如何使用并在实际场景中应用?

    函数模板允许您定义可以处理不同类型参数的函数的通用版本。语法为:template,其中 t 是类型参数。要使用函数模板,请指定所需的参数类型,例如:max(10, 20)。函数模板在排序等实际应用中很有用,例如:template void sort(t arr[], int size)。它们具有通用…

    2026年5月10日
    000
  • C++ 并发编程中内存访问问题及解决方法?

    在 c++++ 并发编程中,共享内存访问问题包括数据竞争、死锁和饥饿。解决方案有:原子操作:确保对共享数据的访问是原子性的。互斥锁:一次只允许一个线程访问临界区。条件变量:线程等待某个条件满足。读写锁:允许多个线程并发读取,但只能允许一个线程写入。 C++ 并发编程中的内存访问问题及解决方案 在多线…

    2026年5月10日
    000
  • c++如何实现函数的重载_c++函数重载实现方法

    函数重载通过参数列表差异实现,如类型、数量或顺序不同,编译器根据实参选择对应函数,返回类型不同不能单独用于重载。 在C++中,函数重载允许在同一作用域内定义多个同名函数,只要它们的参数列表不同(参数个数、类型或顺序不同),编译器会根据调用时传入的实参来选择匹配的函数。函数重载不能仅通过返回类型的不同…

    2026年5月10日
    000

发表回复

登录后才能评论
关注微信