上面代码中有二处bug导致你的想法没有实现
1:锁的一致性没有保证,类ThreadObject中同步代码块中用的锁是当前类的实例,但你在monitor.pulse(newThread)中使用的锁是newThread,二者没有保持一致性,本身就是矛盾的。
2:monitor.pulse()方法必须从同步的代码块内调用。即放在monitor.enter() 与 monitor.exit() 之间调用。修改后的代码,供参考:
using System;
using System.Threading;class Lock
{}class ThreadObject
{
Lock mlock;
public ThreadObject(Lock _lock)
{
mlock=_lock;
}
public void F()
{
lock (this)
{
Console.WriteLine("Thread is working");
Console.WriteLine("Monitor.Wait()");
Monitor.Wait(this);
Console.WriteLine("after Wait");
}
}
}
class testM
{
         
public static void Main()
{
Lock mlock = new Lock();
ThreadObject Tobject = new ThreadObject(mlock);
Thread newThread = new Thread(new ThreadStart(Tobject.F));
newThread.Start();
while (!newThread.IsAlive) ;
Console.WriteLine(newThread.ThreadState);
Console.WriteLine("Monitor.Pulse after 3s"); Thread.Sleep(3000);
Monitor.Enter(mlock);
Monitor.Pulse(mlock);
Monitor.Exit(mlock);
Console.WriteLine("End"); Console.Read();
}
}

解决方案 »

  1.   

    using System;
    using System.Threading;class Lock
    {}class ThreadObject
    {
    Lock mlock;
    public ThreadObject(Lock _lock)
    {
    mlock=_lock;
    }
    public void F()
    {
    lock (mlock)
    {
    Console.WriteLine("Thread is working");
    Console.WriteLine("Monitor.Wait()");
    Monitor.Wait(mlock);
    Console.WriteLine("after Wait");
    }
    }
    }
    class testM
    {
             
    public static void Main()
    {
    Lock mlock = new Lock();
    ThreadObject Tobject = new ThreadObject(mlock);
    Thread newThread = new Thread(new ThreadStart(Tobject.F));
    newThread.Start();
    while (!newThread.IsAlive) ;
    Console.WriteLine(newThread.ThreadState);
    Console.WriteLine("Monitor.Pulse after 3s"); Thread.Sleep(3000);
    Monitor.Enter(mlock);
    Monitor.Pulse(mlock);
    Monitor.Exit(mlock);
    Console.WriteLine("End"); Console.Read();
    }
    }上面的传错了