位置:首頁(yè) > 軟件操作教程 > 編程開(kāi)發(fā) > C# > 問(wèn)題詳情

lock關(guān)鍵字的使用

提問(wèn)人:劉冬梅發(fā)布時(shí)間:2020-10-13

using System;

using System.Threading; 

internal class Account 

{

int balance;

Random r = new Random();

internal Account(int initial) 

{

balance = initial;

internal int Withdraw(int amount)

{

if (balance < 0)

{

//如果balance小于0則拋出異常

throw new Exception("Negative Balance");

}

//下面的代碼保證在當(dāng)前線程修改balance的值完成之前

//不會(huì)有其他線程也執(zhí)行這段代碼來(lái)修改balance的值

//因此,balance的值是不可能小于0的

lock (this)

{

Console.WriteLine("Current Thread:"+Thread.CurrentThread.Name);

//如果沒(méi)有l(wèi)ock關(guān)鍵字的保護(hù),那么可能在執(zhí)行完if的條件判斷之后

//另外一個(gè)線程卻執(zhí)行了balance=balance?amount修改了balance的 值

//而這個(gè)修改對(duì)這個(gè)線程是不可見(jiàn)的,所以可能導(dǎo)致這時(shí)if的條件已經(jīng)

不成立了

//但是,這個(gè)線程卻繼續(xù)執(zhí)行balance=balance?amount,所以導(dǎo)致

balance可能小于0

if (balance >= amount) 

{

Thread.Sleep(5);

balance = balance ? amount;

return amount;

else 

{

return 0; // transaction rejected

} } }

internal void DoTransactions()

{

for (int i = 0; i < 100; i++)

Withdraw(r.Next(?50, 100)); }

internal class Test 

{

static internal Thread[] threads = new Thread[10];

public static void Main()

{

Account acc = new Account (0);

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].Name=i.ToString();

for (int i = 0; i < 10; i++) 

threads[i].Start();

Console.ReadLine(); } }

繼續(xù)查找其他問(wèn)題的答案?

相關(guān)視頻回答
回復(fù)(0)
返回頂部