msdn 上一个关于线程锁的问题,有代码

我看你有戏 2009-09-13 01:41:02

// statements_lock2.cs
using System;
using System.Threading;

class Account
{
int balance;

Random r = new Random();

private static object obj = new object();

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 (this)
lock(obj)
{
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
{
public 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();
}
}
}






我把 lock (this) 用lock(obj)代替,也起到了线程锁的作用,

能否告诉我一下,lock(obj)有什么好处没

网上也有说法但是我不太明白

谢谢了
...全文
59 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
fengjian_428 2009-09-13
  • 打赏
  • 举报
回复
1L说的对
ztenv 2009-09-13
  • 打赏
  • 举报
回复
lock(this)锁住了整个类对象,
lock(obj)以锁住的只是obj,此是可以访问this的其它对象

110,538

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧