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

多线程同步问题
有两个类a,b 和一个窗口
开两个线程,怎样才能执行完a,然后执行b
一、窗口代码
  public partial class Form1 : Form
  {
  a A = new a();
  b B = new b();

  private void button1_Click(object sender, EventArgs e)
  {
  Thread t1=new Thread (new ThreadStart (A.A));
  Thread t2 = new Thread(new ThreadStart(B.B));
  t1.Start ();
  t2.Start();
  }
   
  }

二、a代码
  class a
  {
  public void A()
  {
  //方法A
  }
  }

三、b代码
  class b
  {
  public void B()
  {
  //方法B
  }
  }

请大家指教,最好能贴上修改后的代码

------解决方案--------------------
private void button1_Click(object sender, EventArgs e)
{
Thread t1=new Thread (new ThreadStart (A.A));
Thread t2 = new Thread(new ThreadStart(B.B));
t1.Start ();
t1.Join();
t2.Start();
}
------解决方案--------------------
不要用join, 因为用join 的话就会把UI thread 给block住 等于没用线程,用户按了button1 之后界面会没反映

class A
{
public static readonly object SyncRoot = new object();

public void A()
{
lock( SyncRoot )
{ ... }
}
}

class B
{
public void B()
{
lock( SyncRoot )
{...}
}
}