namespace ThreadAttribute { class Program { static void Main(string[] args) { Account account = new Account(); Thread thread1 = new Thread(new ParameterizedThreadStart(account.WithDraw)); thread1.Name = "小明"; Thread thread2 = new Thread(new ParameterizedThreadStart(account.WithDraw)); thread2.Name = "小红"; thread1.Start(600); thread2.Start(600); Console.ReadKey(); } } public class Account { private static int _balance; public int Blance { get { return _balance; } } public Account() { _balance = 1000; } public void WithDraw(object money) { if ((int)money <= _balance) { Thread.Sleep(2000); _balance = _balance - (int)money; Console.WriteLine("{0} 取钱成功!余额={1}", Thread.CurrentThread.Name, _balance); } else { Console.WriteLine("{0} 取钱失败!余额不足!", Thread.CurrentThread.Name); } } } }
2个线程同时进行了,if ((int)money <= _balance) 判断为true了,锁一下
lock(new object())
{
if ((int)money <= _balance){ do anything....}
}
为避免同时进行,可以再次进行判断
if ((int)money <= _balance){
lock(new object()){
if ((int)money <= _balance){
do....
}
}
}
没有加锁,同时进入去执行了。lock一下,建议google下多线程的相关文章
线程没有锁定资源啊。多搜索一下相关的文章和样例。