多线程互斥实例2

  1using System;
  2using System.Drawing;
  3using System.Collections;
  4using System.ComponentModel;
  5using System.Windows.Forms;
  6using System.Data;
  7// 添加新的命名空间。
  8using System.Threading;
  9
 10namespace ThreadMutex2
 11{
 12    /// <summary>
 13    /// 多线程互斥实例2。
 14    /// </summary>

 15    public class Form1 : System.Windows.Forms.Form
 16    {
 17        private System.Windows.Forms.Button button1;
 18        private System.Windows.Forms.RichTextBox richTextBox1;
 19        /// <summary>
 20        /// 必需的设计器变量。
 21        /// </summary>

 22        private System.ComponentModel.Container components = null;
 23
 24        public Form1()
 25        {
 26            //
 27            // Windows 窗体设计器支持所必需的
 28            //
 29            InitializeComponent();
 30
 31            //
 32            // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
 33            //
 34        }

 35
 36        /// <summary>
 37        /// 清理所有正在使用的资源。
 38        /// </summary>

 39        protected override void Dispose( bool disposing )
 40        {
 41            if( disposing )
 42            {
 43                if (components != null)
 44                {
 45                    components.Dispose();
 46                }

 47            }

 48            base.Dispose( disposing );
 49        }

 50
 51        Windows Form Designer generated code
 97
 98        /// <summary>
 99        /// 应用程序的主入口点。
100        /// </summary>

101        [STAThread]
102        static void Main()
103        {
104            Application.Run(new Form1());
105        }

106        // 定义私有变量。
107        public static Mutex m;
108        public Thread a;
109        public Thread b;
110        // 线程A。
111        public void ThreadA()
112        {
113            while(true)
114            {
115                Form1.m.WaitOne();
116                richTextBox1.Text += "A";
117                Form1.m.ReleaseMutex();
118                Thread.Sleep(10);
119            }

120        }

121        // 线程B。
122        public void ThreadB()
123        {
124            while(true)
125            {
126                Form1.m.WaitOne();
127                richTextBox1.Text += "B";
128                Form1.m.ReleaseMutex();
129                Thread.Sleep(20);
130            }

131        }

132        // 开始多线程。
133        private void button1_Click(object sender, System.EventArgs e)
134        {
135            m = new Mutex();
136            a = new Thread(new ThreadStart(this.ThreadA));
137            b = new Thread(new ThreadStart(this.ThreadB));
138            a.Start();
139            b.Start();
140            button1.Enabled = false;
141        }

142        // 结束多线程。
143        private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
144        {
145            a.Abort();
146            b.Abort();
147        }

148    }

149}

150
posted on 2007-08-22 13:14  Gofficer  阅读(313)  评论(0)    收藏  举报