运行结果:

 

 
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.Threading;  
  10.  
  11. namespace e_7_3_1  
  12. {  
  13.     public partial class Form1 : Form  
  14.     {  
  15.         Thread thread1, thread2;  
  16.         int sum = 0, x = -1;  
  17.         bool mark = false;  
  18.         public Form1()  
  19.         {  
  20.             InitializeComponent();  
  21.             thread1 = new Thread(new ThreadStart(Fun1));  
  22.             thread2 = new Thread(new ThreadStart(Fun2));  
  23.             thread1.Start();    //启动线程  
  24.             thread2.Start();  
  25.         }  
  26.  
  27.         private void button1_Click(object sender, EventArgs e)  
  28.         {  
  29.             label1.Text = sum.ToString();   //显示数据  
  30.         }  
  31.  
  32.         public void Fun1()              //生产数据  
  33.         {  
  34.             for (int k = 1; k < 5; k++)  
  35.             {  
  36.                 Monitor.Enter(this);        //这里this是Form1类对象,得到this的对象锁  
  37.                 if (mark)                 
  38.                     Monitor.Wait(this);    //如果消费者数据未取走,释放对象锁,生产者等待  
  39.                 mark = !mark;  
  40.                 x = k;  
  41.                 Monitor.Pulse(this);        //激活消费者线程  
  42.                 Monitor.Exit(this);         //释放this的对象锁  
  43.             }  
  44.         }  
  45.  
  46.         public void Fun2()             //消费数据  
  47.         {  
  48.             for (int k = 0; k < 4; k++)  
  49.             {  
  50.                 Monitor.Enter(this);  
  51.                 if (!mark)  
  52.                     Monitor.Wait(this);     //如果生产者未放数据,消费之等待  
  53.                 mark = !mark;  
  54.                 sum += x;  
  55.                 Monitor.Pulse(this);  
  56.                 Monitor.Exit(this);  
  57.             }  
  58.         }  
  59.     }  
  60. }