C#一个多线程实例的疑问
[code=C#][/code]public partial class Form1 : Form
{
Thread thread1, thread2;
int num = 0;
int[] a1 = new int[4]{0,0,0,0};
int[] a2 = new int[4]{0,0,0,0};
private delegate void delFun();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
thread1 = new Thread(new ThreadStart(Invoke_Fun1));
thread1.IsBackground = true;
thread1.Priority = ThreadPriority.Normal;
thread2 = new Thread(new ThreadStart(Invoke_Fun2));
thread2.IsBackground = true;
thread2.Priority = ThreadPriority.Normal;
thread1.Start();
thread2.Start();
}
private void Invoke_Fun1()
{
BeginInvoke(new delFun(Fun1));
}
private void Invoke_Fun2()
{
BeginInvoke(new delFun(Fun2));
}
public void Fun1()
{
int k, n;
for (k = 0; k < 4; k++)
{
n = num;
Thread.Sleep(25);
num = n + 1;
a1[k] = num;
}
label1.Text = Convert.ToString(num);
label2.Text = "";
for (k = 0; k < 4; k++)
label2.Text += Convert.ToString(a1[k]);
}
public void Fun2()
{
int k, n;
for (k = 0; k < 4; k++)
{
n = num;
Thread.Sleep(15);
num = n + 1;
a2[k] = num;
}
label1.Text = Convert.ToString(num);
label3.Text = "";
for (k = 0; k < 4;k++ )
label3.Text += Convert.ToString(a2[k]);
}
}
这是一段很简单的代码,界面编辑器里面只有3个Label。这段代码的执行结果让我不理解:Label1始终显示8;Label2显示1234(或5678);Label3显示5678(或1234)!
我的疑问:既然thread1和thread2是两个不相干的线程,且优先级都一样,为什么这里结果且标明:要么thread1执行完毕后thread2才开始执行,要么thread2执行完毕后thread1才开始执行?
求大家指点~~小弟不甚感激呀!
------解决方案--------------------
这种调用写法好繁琐,有必要单独写个委托方法?