Lock只管同一代码块保证只有一个线程进入。多个代码块要用AutoResetEvent: class Program
{
static void Main(string[] args)
{
Program p = new Program(); Thread t1 = new Thread(new ThreadStart(p.FunctionA));
Thread t2 = new Thread(new ThreadStart(p.FunctionB));
t1.Start();
Thread.Sleep(10);
t2.Start();
} private static AutoResetEvent allDown = new AutoResetEvent(true); public void FunctionA()
{
allDown.Reset();
DoWorkA();
allDown.Set();
} public void FunctionB()
{
allDown.WaitOne();
DoWorkB();
} public void DoWorkA()
{
Console.WriteLine("A started.");
Thread.Sleep(2000);
Console.WriteLine("A is running.");
Thread.Sleep(2000);
Console.WriteLine("A is Done.");
} public void DoWorkB()
{
Console.WriteLine("B started.");
Thread.Sleep(1000);
Console.WriteLine("B is running.");
Thread.Sleep(1000);
Console.WriteLine("B is Done.");
}
}
{
static void Main(string[] args)
{
Program p = new Program(); Thread t1 = new Thread(new ThreadStart(p.FunctionA));
Thread t2 = new Thread(new ThreadStart(p.FunctionB));
t1.Start();
Thread.Sleep(10);
t2.Start();
} private static AutoResetEvent allDown = new AutoResetEvent(true); public void FunctionA()
{
allDown.Reset();
DoWorkA();
allDown.Set();
} public void FunctionB()
{
allDown.WaitOne();
DoWorkB();
} public void DoWorkA()
{
Console.WriteLine("A started.");
Thread.Sleep(2000);
Console.WriteLine("A is running.");
Thread.Sleep(2000);
Console.WriteLine("A is Done.");
} public void DoWorkB()
{
Console.WriteLine("B started.");
Thread.Sleep(1000);
Console.WriteLine("B is running.");
Thread.Sleep(1000);
Console.WriteLine("B is Done.");
}
}
可以给每个线程起个名字, 或打印线程ID.
如果是同一个线程进入了, 那就不奇怪了.
一个线程,在FA中取得锁, 当他没有释放锁, 又进入FB, 它依然是持有锁的, 不会被阻挡.
也有可能是运行过程中_LockObj发生改变,进入FA和进入FB的线程实际上拥有不同的锁。