我目前的理解,lock()内的对象就是在这个对象上设置了一个值。我的问题是,难道加了lock就自动为这个对象创造这个属性么,它可以单独得到么。编译器依靠什么来使之具有安全性。另一个问题是,如果放进去的是一个值对象,那会怎么样呢
解决方案 »
- html问题
- 【求助】C# Winform xml怎么能和exe打包在一起
- 大量消息定制带来的问题
- DataTable取值问题,急!搞定就给分了
- 取上月数据的存储过程..请帮忙..简单.散分快
- C# 多线程调用C++Dll中同一函数出现问题!!!
- 求助:C#.net如何制作安装程序,安装程序能够自动创建oracle表空间、用户,并创建数据表?
- WPF,麻烦给一个Blend的中文教材
- 在WPF中使用webBrowser,如何设置元素焦点,如何自点击
- 怎样用.net做滚动条呀,请大家帮忙!
- C#插入sql server 2000记录出错
- How to determine is there any data stored on the clipboard in C#?
using System;
using System.Threading;class Account
{
private Object thisLock = new Object();
int balance; Random r = new Random(); public Account(int initial)
{
balance = initial;
} int Withdraw(int amount)
{ // This condition will never be true unless the lock statement
// is commented out:
if (balance < 0)
{
throw new Exception("Negative Balance");
} // Comment out the next line to see the effect of leaving out
// the lock keyword:
lock(thisLock)
{
if (balance >= amount)
{
Console.WriteLine("Balance before Withdrawal : " + balance);
Console.WriteLine("Amount to Withdraw : -" + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
return amount;
}
else
{
return 0; // transaction rejected
}
}
} public void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(1, 100));
}
}
}class Test
{
static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account(1000);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
}
}
___________________________________________________________这个不太确切. 在.NET里Object的Lock同步机制是这样的:每一个System.Object 产生实例的时候,它内部都有一个特殊的SyncBlockIndex , 而lock 的实质只是从内存的 SyncBlocks 表中取出一个可用的,并把它的Index 存到 Object 的 SyncBlockIndex 中.详细解释请看大师Jeffrey Ritcher 写的这篇文章,把.NET的同步机制交代的十分彻底:http://msdn.microsoft.com/msdnmag/issues/03/01/NET/
___________________________________________
把值对象Boxing成一个Object再加锁.