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("余额为负"); 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++) //当num>=6时出现问题,没有打印"number:1",但num=1-5时是正常的。 { 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贡献1812条经验 获得超5个赞
i < num ,而 num = 6
num > = 6 时, 退出 for 循环,WithDraw(r.Next(1, 100)); 就不执行了.
- 5 回答
- 0 关注
- 330 浏览
添加回答
举报
0/150
提交
取消