Lock(this)与Lock(Typeof(class))区别
时间:2011-12-12
来源:互联网
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)有什么区别
作者: lifanghui1 发布时间: 2011-12-12
该回复于2011-12-12 10:06:15被管理员删除
- 对我有用[0]
- 丢个板砖[0]
- 引用
- 举报
- 管理
- TOP
|
#2楼 得分:0回复于:2011-12-12 09:51:31
|
作者: jhdxhj 发布时间: 2011-12-12
lock(this) 只对当前实例同步
作者: ohkuy 发布时间: 2011-12-12
lock(typeof(squareclass)) 相当于所有 squareclass 实例同步
lock(this) 只对当前实例同步
+
作者: fangxinggood 发布时间: 2011-12-12
squareclass s1 = new squareclass(); 线程1
squareclass s2 = new squareclass(); 线程2
如果是lock(this),是无法控制线同步的。
而lock(typeof(squareclass))则是可以控制线同步的了。
作者: ajaxtop 发布时间: 2011-12-12
squareclass s1 = new squareclass(); 线程1
squareclass s2 = new squareclass(); 线程2
如果是lock(this),是无法控制线程同步的。
而lock(typeof(squareclass))则是可以控制线程同步的了。
作者: lifanghui1 发布时间: 2011-12-12
那也就是说,在不同线程分别中定义
squareclass s1 = new squareclass(); 线程1
squareclass s2 = new squareclass(); 线程2
如果是lock(this),是无法控制线程同步的。
而lock(typeof(squareclass))则是可以控制线程同步的了。
要看方法操作的是否是同一实例
作者: lifanghui1 发布时间: 2011-12-12
目前比较多的是对私有静态变量枷锁。例如C# code
private static object lockFlag= new object();C# code
lock(lockFlag) { ..... }
作者: Sandy945 发布时间: 2011-12-13
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28