关于lock的一些疑问
以下是MSDN文档里面的代码,
说用了lock锁住了,balance永远不会小于0,为什么呢?
意思是不是说,只执行lock大括号里面的代码,那个 if (balance < 0)就不执行了?
请知道的人解释清楚一下,非常感谢
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)
{
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 Withdraw1: " + balance);
Console.WriteLine("Amount to Withdraw : " + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
return amount;
}
else
{
return 0;
}
}
}
public void DoTransactions()
{
for (int i = 0; i < 100; i++)
Withdraw(r.Next(1,100));
}
}
class Text
{
static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account(100);
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();
}//此处用2个循环,我把 threads[i].Start();放在第一个循环里面,运行结果也一样,我觉得好像没多大区别
Console.Read();
}
}
说用了lock锁住了,balance永远不会小于0,为什么呢?
意思是不是说,只执行lock大括号里面的代码,那个 if (balance < 0)就不执行了?
请知道的人解释清楚一下,非常感谢
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)
{
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 Withdraw1: " + balance);
Console.WriteLine("Amount to Withdraw : " + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
return amount;
}
else
{
return 0;
}
}
}
public void DoTransactions()
{
for (int i = 0; i < 100; i++)
Withdraw(r.Next(1,100));
}
}
class Text
{
static void Main()
{
Thread[] threads = new Thread[10];
Account acc = new Account(100);
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();
}//此处用2个循环,我把 threads[i].Start();放在第一个循环里面,运行结果也一样,我觉得好像没多大区别
Console.Read();
}
}
...全文
相关推荐
2021-2022年收藏的精品资料中考反义疑问句知识点习题带答案.doc
精品教育教学资料
河南专用2020版中考英语语法过关专题十三简单句陈述句感叹句疑问句祈使句课件人教新目标版20200530474
河南专用2020版中考英语语法过关专题十三简单句陈述句感叹句疑问句祈使句课件人教新目标版20200530474
新版译林版六年级上册总复习试卷精选.doc
新版译林版六年级上册总复习试卷精选.doc
七年级英语下册Unit5Whydoyoulikepandas语法点滴素材3新版人教新目标版
七年级英语下册Unit5Whydoyoulikepandas语法点滴素材3新版人教新目标版
Ubuntu“无法打开锁文件(Could not get lock)”问题解决方法
主要介绍了Ubuntu“无法打开锁文件(Could not get lock)”问题解决方法 ,需要的朋友可以参考下


