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)有什么区别
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)有什么区别
squareclass s1 = new squareclass(); 线程1
squareclass s2 = new squareclass(); 线程2
如果是lock(this),是无法控制线同步的。
而lock(typeof(squareclass))则是可以控制线同步的了。
squareclass s1 = new squareclass(); 线程1
squareclass s2 = new squareclass(); 线程2
如果是lock(this),是无法控制线程同步的。
而lock(typeof(squareclass))则是可以控制线程同步的了。
{
.....
}