好友
阅读权限10
听众
最后登录1970-1-1
|
sijin
发表于 2008-11-24 22:14
namespace ThreadExample
{
public partial class Form1 : Form
{
StringBuilder sb = new StringBuilder();
Thread thread1;
Thread thread2;
public Form1()
{
InitializeComponent();
}
private void AppendString(string s)
{
lock (sb)
{
sb.Append(s);
}
}
public void Method1()
{
while (true)
{
Thread.Sleep(100); //线程休眠100毫秒
AppendString("a");
}
}
public void Method2()
{
while (true)
{
Thread.Sleep(100); //线程休眠100毫秒
AppendString("b");
}
}
private void buttonStart_Click(object sender, EventArgs e)
{
sb.Remove(0, sb.Length);
timer1.Enabled = true;
thread1 = new Thread(new ThreadStart(Method1));
thread2 = new Thread(new ThreadStart(Method2));
thread1.Start();
thread2.Start();
}
private void buttonAbort_Click(object sender, EventArgs e)
{
thread1.Abort();
thread1.Join(10);
thread2.Abort();
thread2.Join(10);
}
private void timer1_Tick(object sender, EventArgs e)
{
if (thread1.IsAlive == true || thread2.IsAlive == true)
{
richTextBox1.Text = sb.ToString();
}
else
{
timer1.Enabled = false;
}
}
}
}
[ 本帖最后由 sijin 于 2008-11-24 22:21 编辑 ] |
|
发帖前要善用【论坛搜索】功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。 |
|
|
|
|