Below is the example of lock statement of C sharp, try to run this program and see what output it shows:
Code:
class AccountGH
{ int balanceM;
Random r = new Random();
public Account(int initial)
{ balanceM = initial;
}
int Withdraw(int amount)
{ if (balanceM < 0)
{throw new Exception("Negative balanceM"); }
lock (this)
{
if (balanceM >= amount)
{
Console.WriteLine("balanceM before Withdrawal : " + balanceM);
Console.WriteLine("Amount to Withdraw : -" + amount);
balanceM = balanceM - amount;
Console.WriteLine("balanceM after Withdrawal : " + balanceM);
return amount;
}
else
{ return 0;
} } }
public void DoTransactions()
{
for (int i = 0; i < 100; i++)
{
Withdraw(r.Next(1, 100));
}
}
}
Bookmarks