服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#多线程经典示例(吃苹果)

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

2021-12-18 15:23飞翔的月亮 C#

本文主要讲述了多线程开发中经典示例,通过本示例,可以加深对多线程的理解。下面跟着小编一起来看下吧

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

示例概述:

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

涉及到知识点:

  • 线程Thread 创建并控制线程,设置其优先级并获取其状态。
  • 锁 lock 用于实现多线程同步的最直接办法就是加锁,它可以把一段代码定义为互斥段,在一个时刻内只允许一个线程进入执行,而其他线程必须等待。
  • 事件EventHandler 声明一个事件,用于通知界面做改变

设计思路:

  • Productor 表示生产者,用于削苹果。
  • Consumer 表示消费者,用于吃苹果。
  • Dish 盘子,用于装苹果,做为中间类
  • EatAppleSmp 的BeginEat()方法,表示开始吃苹果,启动线程

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

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

后台输出如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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 代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace DemoSharp.EatApple
{
 /// <summary>
 /// 生产者
 /// </summary>
 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代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace DemoSharp.EatApple
{
 /// <summary>
 /// 消费者
 /// </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;//声明一个事件,当放苹果时触发该事件
  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;
    }
   }
  }
 }
}

Dish代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace DemoSharp.EatApple
{
 /// <summary>
 /// 盘子,属于中间类
 /// </summary>
 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();
  /// <summary>
  /// 构造函数,初始化Dish对象
  /// </summary>
  /// <param name="num">表示削够多少个苹果结束</param>
  public Dish(int num)
  {
   this.EnabledNum = num;
  }
  /// <summary>
  /// 放苹果的方法
  /// </summary>
  /// <param name="name"></param>
  ///<returns>是否放成功</returns>
  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;
   }
  }
  /// <summary>
  /// 取苹果的方法
  /// </summary>
  /// <param name="name"></param>
  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代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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;//声明一个事件,当放苹果时触发该事件
  /// <summary>
  /// 开始吃苹果
  /// </summary>
  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);
   }
  }
 }
}

界面类代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
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>
 /// 页面类
 /// </summary>
 public partial class EatAppleForm : Form
 {
  private EatAppleSmp m_EatAppleSmp = new EatAppleSmp();
  public EatAppleForm()
  {
   InitializeComponent();
   InitView();
   m_EatAppleSmp.PutAction += PutActionMethod;
   m_EatAppleSmp.GetAction += GetActionMethod;
  }
  /// <summary>
  /// 初始化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>
  /// 启动线程
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  private void btnStart_Click(object sender, EventArgs e)
  {
   this.m_EatAppleSmp.BeginEat();
  }
  /// <summary>
  /// 放苹果事件
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  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);
    }
   }
  }
  /// <summary>
  /// 吃苹果事件
  /// </summary>
  /// <param name="sender"></param>
  /// <param name="e"></param>
  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);
    }
   }
  }
  /// <summary>
  /// 往指定的GroupBox中添加对象
  /// </summary>
  /// <param name="gbView"></param>
  /// <param name="lbl"></param>
  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();
   }));
  }
 }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持服务器之家!

原文链接:http://www.cnblogs.com/hsiang/p/6267147.html

延伸 · 阅读

精彩推荐
  • C#Unity3D实现虚拟按钮控制人物移动效果

    Unity3D实现虚拟按钮控制人物移动效果

    这篇文章主要为大家详细介绍了Unity3D实现虚拟按钮控制人物移动效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一...

    shenqingyu060520232410972022-03-11
  • C#WPF 自定义雷达图开发实例教程

    WPF 自定义雷达图开发实例教程

    这篇文章主要介绍了WPF 自定义雷达图开发实例教程,本文介绍的非常详细,具有参考借鉴价值,需要的朋友可以参考下...

    WinterFish13112021-12-06
  • C#深入解析C#中的交错数组与隐式类型的数组

    深入解析C#中的交错数组与隐式类型的数组

    这篇文章主要介绍了深入解析C#中的交错数组与隐式类型的数组,隐式类型的数组通常与匿名类型以及对象初始值设定项和集合初始值设定项一起使用,需要的...

    C#教程网6172021-11-09
  • C#C#实现XML文件读取

    C#实现XML文件读取

    这篇文章主要为大家详细介绍了C#实现XML文件读取的相关代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    Just_for_Myself6702022-02-22
  • C#C#裁剪,缩放,清晰度,水印处理操作示例

    C#裁剪,缩放,清晰度,水印处理操作示例

    这篇文章主要为大家详细介绍了C#裁剪,缩放,清晰度,水印处理操作示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    吴 剑8332021-12-08
  • C#C#设计模式之Visitor访问者模式解决长隆欢乐世界问题实例

    C#设计模式之Visitor访问者模式解决长隆欢乐世界问题实例

    这篇文章主要介绍了C#设计模式之Visitor访问者模式解决长隆欢乐世界问题,简单描述了访问者模式的定义并结合具体实例形式分析了C#使用访问者模式解决长...

    GhostRider9502022-01-21
  • C#C# 实现对PPT文档加密、解密及重置密码的操作方法

    C# 实现对PPT文档加密、解密及重置密码的操作方法

    这篇文章主要介绍了C# 实现对PPT文档加密、解密及重置密码的操作方法,非常不错,具有参考借鉴价值,需要的朋友可以参考下...

    E-iceblue5012022-02-12
  • C#C#通过KD树进行距离最近点的查找

    C#通过KD树进行距离最近点的查找

    这篇文章主要为大家详细介绍了C#通过KD树进行距离最近点的查找,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    帆帆帆6112022-01-22