using System;
using System.Threading;
namespace LockTest{??? class Account??? {??????? private object thisLock = new object();??????? double balance;
??????? Random r = new Random();??????? public int number = 0;
??????? public Account(double Initial)??????? {??????????? balance = Initial;??????? }??????? double WithDraw(double amount)??????? {??????????? ??????????? if (balance < 0)??????????????? throw new Exception("余額為負(fù)");??????????? lock (thisLock)??????????? {??????????????? if (balance >= amount)??????????????? {??????????????????? number++;??????????????????? Console.WriteLine("number:" + number);??????????????????? Console.WriteLine("取款前余額:{0}", balance);??????????????????? Console.WriteLine("取款:{0}:", amount);??????????????????? balance -= amount;??????????????????? Console.WriteLine("取款后余額:{0}\n", balance);??????????????????? return amount;??????????????? }??????????????? else??????????????? {??????????????????? Console.WriteLine("余額不足");??????????????????? return 0;??????????????? }??????????? }?????????? ??????? }??????? public void DoTransactions()??????? {??????????? int num = 6;??????????? for (int i = 0; i < num; i++)? //當(dāng)num>=6時(shí)出現(xiàn)問題,沒有打印"number:1",但num=1-5時(shí)是正常的。??????????? {??????????????? WithDraw(r.Next(1, 100));??????????? }?????????? ??????? }??? }
??? class Program??? {??????? static void Main(string[] args)??????? {??????????? Thread[] threads = new Thread[10];??????????? Account acc = new Account(10000);??????????? for (int i = 0; i < 10; i++)??????????? {??????????????? Thread t = new Thread(new ThreadStart(acc.DoTransactions));??????????????? threads[i]=t;??????????????? threads[i].Start();??????????? }??????????? //for (int i = 0; i < 10; i++)??????????? //{??????????? //??? threads[i].Start();??????????? //}??????? }??? }}
5 回答

ABOUTYOU
TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個(gè)贊
?i < num ,而 num = 6
num > = 6 時(shí), 退出 for 循環(huán),WithDraw(r.Next(1, 100)); 就不執(zhí)行了.

婷婷同學(xué)_
TA貢獻(xiàn)1844條經(jīng)驗(yàn) 獲得超8個(gè)贊
?我把你的代碼運(yùn)行了一下,沒有任何問題,即使把num改成26也沒有問題啊,不會(huì)出現(xiàn)你說的那種情況,你再試一下,是不是看錯(cuò)了

料青山看我應(yīng)如是
TA貢獻(xiàn)1772條經(jīng)驗(yàn) 獲得超8個(gè)贊
@碼魔谷:CMD不夠行輸出.你把 Console.WriteLine 改成 Debug.WriteLine,然后從VS的輸出窗口中查看結(jié)果.
- 5 回答
- 0 關(guān)注
- 352 瀏覽
添加回答
舉報(bào)
0/150
提交
取消