初次接触多程序同步, 很是头疼, 望各位前辈帮帮小弟, 先谢了
namespace ThreadDemo
{
    public partial class Form1 : Form
    {
        private Yan y = new Yan();        public Form1()
        {
            InitializeComponent();        }        private void button1_Click(object sender, EventArgs e)
        {
            Thread t1 = new Thread(T1);
            t1.Name = "t1";
            Thread t2 = new Thread(T2);
            t2.Name = "t2";            t1.Start();
            t2.Start();
        }        private void T1()
        {
            lock (y)
            {
                for (int i = 0; i < 10000000; ++i) ;
                y.str = "先";
                MessageBox.Show(y.str);
            }
             
        }        private void T2()
        {
            y.str = "后";
            MessageBox.Show(y.str);
        }
    }    public class Yan
    {
        public string str = "";
    }
}
我让他先弹出“先”, 然后再弹出“后”, 怎么搞?求解, 谢谢!!!

解决方案 »

  1.   

    呵呵,你用的是lock,相当于临界区,临界区无法做到控制线程执行的先后次序,只能控制两段代码不同时运行,
      

  2.   

    谢谢!!!发贴后又试了一下, 得这样才可以!!!
            private void T2()
            {
                lock (y)
                {
                    y.str = "后";
                    MessageBox.Show(y.str);
                }
            }
    t2中也得加lockThanks
      

  3.   

    而且你在T2中也没有lock(y)这是不对的,凡是修改共享资源都要lock,要控制线程先后,你这个需求最简单的方法是用ManualResetEvent控制,当然信号量也可以,ManualResetEvent manualEvent=new ManualResetEvent(false);        private void T1()
            {
                lock (y)
                {
                    for (int i = 0; i < 10000000; ++i) ;
                    y.str = "先";
                    MessageBox.Show(y.str);
                }
                manualEvent.Set();
                 
            }        private void T2()
            {
              manualEvent.WaitOne();          lock(y)
    {
                y.str = "后";
                MessageBox.Show(y.str);
    }
            }