日期:2014-05-17 浏览次数:20884 次
namespace WindowsFormsApplication2 { class Class1 { public volatile bool shouldStop; private Form1 form; public Class1(Form1 form) { this.form = form; } public void Method1(object obj) { string s = obj as string; form.AddMessage(s); while (shouldStop == false) { Thread.Sleep(1000);//将当前线程阻塞,线程1休眠100毫秒 form.AddMessage("a"); } form.AddMessage("\n线程Method1已经终止"); } public void Method2(object obj) { while (shouldStop == false) { Thread.Sleep(1000);//将当前线程阻塞,线程2休眠100毫秒 form.AddMessage("b"); } form.AddMessage("\n线程Method2已经终止"); } } }
namespace WindowsFormsApplication2 { public partial class Form1 : Form { Thread thread1, thread2; Class1 cls; public Form1() { InitializeComponent(); cls = new Class1(this); } private void btnStart_Click(object sender, EventArgs e) { richTextBox1.Clear(); cls.shouldStop = false; thread1 = new Thread(cls.Method1); thread1.IsBackground = true; thread2 = new Thread(cls.Method2); thread2.IsBackground = true; thread1.Start("a method start\n"); thread2.Start(); } private delegate void AddMessageDelegate(string message); public void AddMessage(string s) { if (richTextBox1.InvokeRequired == true) { AddMessageDelegate d = AddMessage; richTextBox1.Invoke(d, s); } else { richTextBox1.AppendText(s); } } private void btnStop_Click(object sender, EventArgs e) { cls.shouldStop = true; thread2.Join(2000); //总是先是线程2结束,然后线程1结束 thread1.Join(5000); /* * thread1.Join(0);//问题1:总是先是线程2结束,然后线程1结束,为什么? * thread2.Join(0); //问题2:看了参数表是时间,这里参数为0是表示 立即么?和无参数有什么区别? */ } } }