源码如下:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Threading;namespace PracticeThreadAppendString{ public partial class threadAppendStrForm : Form { StringBuilder sb = new StringBuilder(); Thread threadA, threadB; public bool isStart = false; private void appendString(string s) { lock (sb) { sb.Append(s); } } private void methodA() { while (true) { if( !this.isStart){ break; } Thread.Sleep(100); appendString("A"); } } private void methodB() { while (true) { if( !this.isStart){ break; } Thread.Sleep(100); appendString("B"); } } public threadAppendStrForm() { InitializeComponent(); } private void startThreadButton_Click(object sender, EventArgs e) { if (this.isStart) { return; } this.isStart = true; //清空缓冲区 sb.Remove(0, sb.Length); appendStrTimer.Enabled = true; threadA = new Thread(new ThreadStart(methodA)); threadB = new Thread(new ThreadStart(methodB)); threadA.Start(); threadB.Start(); } private void exitThreadButton_Click(object sender, EventArgs e) { this.isStart = false; } private void appendStrTimer_Tick(object sender, EventArgs e) { if(threadA.IsAlive == true || threadB.IsAlive == true){ showRichTextBox.Text = sb.ToString(); }else{ appendStrTimer.Enabled = false; } } }}
效果如下: