using System;
using System.Collections.Generic;
using System Text;
using System Threading;
namespace synch ronoustest
{
  public class squareclass
 {
   public double num;
  public double square;
  public void Calcsquare ()
  {
      //使用Lock 对类squareclass 加锁
   lock (typeof(squareclass))
   {
    square = num * num;
    Console.WriteLine("{ 0 } is executing Calcsquare ( ) , { 1 } * { 2 } = { 3 }" ,
        Thread.CurrentThread.Name, num , num , square) ;
   }
   Console.WriteLine() ;
   }
  }
  class Program
  {
   stat ic void Main (string[ ] args)
  {
    Console.WriteLine ( " *** synchronizing thread example *** /n" ) ;
    squareclass s = new squareclass() ;
    //使五个线程全部指向同一对象的同一方法
    Thread[ ] threads = new Thread [5 ];
    for ( int i = 0; i < 5; i++ )
    {
      threads[i] = new Thread( new ThreadStart(s.Calcsquare)) ;
      threads[i].Name = string.Format ("workerthread {0}" , i) ;
    }
    s.num = 0;
    //现在开始每个线程
    foreach (Thread t in threads)
    {
     s.num = s.num + 1;
     t.Start () ;
    }
    Console.ReadLine() ;
   }
  }
}
请问红色部分lock(typeof(squareclass))改为Lock(This)有什么区别

解决方案 »

  1.   

    lock(typeof(squareclass)) 相当于所有 squareclass 实例同步lock(this) 只对当前实例同步
      

  2.   

    那也就是说,在不同线程分别中定义
                     squareclass s1 = new squareclass(); 线程1
                   squareclass s2 = new squareclass(); 线程2
              如果是lock(this),是无法控制线同步的。
               而lock(typeof(squareclass))则是可以控制线同步的了。
      

  3.   

    那也就是说,在不同线程分别中定义
      squareclass s1 = new squareclass(); 线程1
      squareclass s2 = new squareclass(); 线程2
      如果是lock(this),是无法控制线程同步的。
      而lock(typeof(squareclass))则是可以控制线程同步的了。 
      

  4.   

    一个对lock太扩大化,为“死锁”制造机会。另外一个根本不能锁。目前比较多的是对私有静态变量枷锁。例如private static object lockFlag= new object();lock(lockFlag)
    {
        .....
    }