日期:2014-05-18  浏览次数:20661 次

关于多线程的疑惑
小弟写了个多线程的测试,为何最后显示的出来的结果有时是0,有时是50呢,愿各位大侠不吝赐教啊,代码如下:
C# code
public partial class MainPage : PhoneApplicationPage
    {
        int num = 0;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            Thread th1 = new Thread(new ThreadStart(GetNum));
            Thread th2 = new Thread(new ThreadStart(GetNum));

            th1.Start();
            th2.Start();

            textBlock1.Text = num.ToString();
        }

        private void GetNum()
        {
            for (int i = 0; i < 50; i++)
            {
                num++;
            }
        }
    }


------解决方案--------------------
因为你没有加锁,两个线程会互相干扰,而且,你没有等待线程结束,所以执行 num.ToString时,线程可能还在运行,num的值随机