运行结果:
- 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 System.Threading;
- namespace e_7_3_1
- {
- public partial class Form1 : Form
- {
- Thread thread1, thread2;
- int sum = 0, x = -1;
- bool mark = false;
- public Form1()
- {
- InitializeComponent();
- thread1 = new Thread(new ThreadStart(Fun1));
- thread2 = new Thread(new ThreadStart(Fun2));
- thread1.Start(); //启动线程
- thread2.Start();
- }
- private void button1_Click(object sender, EventArgs e)
- {
- label1.Text = sum.ToString(); //显示数据
- }
- public void Fun1() //生产数据
- {
- for (int k = 1; k < 5; k++)
- {
- Monitor.Enter(this); //这里this是Form1类对象,得到this的对象锁
- if (mark)
- Monitor.Wait(this); //如果消费者数据未取走,释放对象锁,生产者等待
- mark = !mark;
- x = k;
- Monitor.Pulse(this); //激活消费者线程
- Monitor.Exit(this); //释放this的对象锁
- }
- }
- public void Fun2() //消费数据
- {
- for (int k = 0; k < 4; k++)
- {
- Monitor.Enter(this);
- if (!mark)
- Monitor.Wait(this); //如果生产者未放数据,消费之等待
- mark = !mark;
- sum += x;
- Monitor.Pulse(this);
- Monitor.Exit(this);
- }
- }
- }
- }