◆◆◆◆◆◆◆◆◆◆ 线程同步?(请指教!) ◆◆◆◆◆◆◆◆◆◆
首先 感谢 大家能看下去,因为代码有点长,如果在线看不明,可以复制 到visual studio 上去调试,只要增加 两个控件就行,
先列出几个要点:
下面的什么意思:
- C# code
this.Invoke(fc);// Monitor.Wait(this);// Monitor.Exit(this);//释放排他销
// 下面代码 用到了 两个控件
- C# code
// 1 richTextBox rtbShow;//用来显示信息的 // 2 button btn122 //是开始测试用的。
代码 开始: (以下代码有错,请指出,谢谢!)
- C# code
private delegate void FlushClient();//代理private static int MyCounter = 0;////使用Monitor 同步两个线程private void btn122_Click(object sender, EventArgs e){ MyCounter = 0;//作为计数器 rtbShow.Text = ""; ThreadStart tsA = new ThreadStart(this.ta); Thread threadA = new Thread(tsA); threadA.IsBackground = true; threadA.Start(); rtbShow.Text = "线程A已经启动!"; ThreadStart tsB = new ThreadStart(this.tb); Thread threadB = new Thread(tsA); threadB.IsBackground = true; threadB.Start(); rtbShow.Text = "线程B已经启动!"; // 阻塞 主线程: threadA.Join(); threadB.Join();}//private static int MyCounter = 0;//作为计数器//要同步的线程Aprivate void ta(){ FlushClient fc = new FlushClient(ThreadA); this.Invoke(fc);}private void tb(){ FlushClient fc = new FlushClient(ThreadB); this.Invoke(fc);}private void ThreadA(){ try { Monitor.Enter(this);//获得 排他销 if (MyCounter < 10) { rtbShow.Text = "当前计数器:" + MyCounter.ToString() + "小于 10 ;线程在等等中。\n"; Monitor.Wait(this);// } rtbShow.AppendText("启动线程计数器!\n"); while (MyCounter > 0) { MyCounter--; rtbShow.AppendText("\n"+"当前计数器值:"+MyCounter.ToString()); Thread.Sleep(50); } } catch (Exception ex) { } finally { Monitor.Exit(this);//释放排他销 }}//要同步的线程Bprivate void ThreadB(){ try { Monitor.Enter(this);//获得 排他销 this.rtbShow.AppendText("启动线程2 增加计数!\n"); while (MyCounter < 10) { MyCounter++; rtbShow.AppendText("\n当前计数器值:" + MyCounter.ToString()); Thread.Sleep(50); } rtbShow.AppendText("\n线程二 增加计数器 操作完成,再次启动线程 一:\n"); Monitor.Pulse(this); } catch (Exception ex) { } finally { Monitor.Exit(this);//释放排他销 }}
◆◆◆◆◆◆◆◆◆◆ 线程同步?(请指教!) ◆◆◆◆◆◆◆◆◆◆
------解决方案--------------------------------------------------------
- C# code
ThreadStart tsB = new ThreadStart(this.tb); Thread threadB = new Thread[color=#FF0000](tsA);[/color][b][/b] threadB.IsBackground = true; threadB.Start(); rtbShow.Text = "线程B已经启动!";