先插代码如下:using System;
namespace ThisApplication
{
    class refInt
    {
        internal int X { get; set; }
        internal refInt( int x )
        {
            X = x;
        }
        public override string ToString( )
        {
            return X.ToString( );
        }
    }
    class A
    {
        internal A( )
        {
            x = new refInt( 10 );
        }
        internal refInt x { get; private set; }
        internal void DoX( )
        {
            while( true )
            {
                lock( x )
                {
                    Console.WriteLine( string.Format( "--{0}--", x ) );
                    x.X++;
                }

            }
        }
    }
    class B
    {
        A a;
        refInt x;
        internal B( int k )
        {
            a = new A( );
            System.Threading.ThreadStart t = new System.Threading.ThreadStart( a.DoX );
            System.Threading.Thread td = new System.Threading.Thread( t );
            td.Start( );
            while( true )
            {
                x = a.x;

                Console.WriteLine( string.Format( "//{0}\\\\", x ) );
                x.X++;
                Console.WriteLine( string.Format( "\\\\{0}//", x ) );

            }
        }
    }
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main( )
        {
            B b = new B( 1 );
        }
    }
}最后输出的结果是DoX( )与B( int k )的输出交错的,并且是顺序递增的,以此来看,没有被锁?????

解决方案 »

  1.   

    B的构造函数里也需要加锁,否则又有什么意义呢?            while( true )
                {
                    lock(a.x)
                    {
                      x = a.x;
                      Console.WriteLine( string.Format( "//{0}\\\\", x ) );
                      x.X++;
                      Console.WriteLine( string.Format( "\\\\{0}//", x ) );
                    }
                }
      

  2.   

    对class B
    中共享资源   refInt x;进行操作的时候.
    你没有加锁,何来被锁.
    你锁的只是class A 中A.DoX中的操作