首页 新闻 赞助 找找看

关于线程的疑问,为什么会输出-200

0
悬赏园豆:5 [已解决问题] 解决于 2013-12-09 20:18
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);
            }

        }
    }
}
复制代码

太笼统的主页 太笼统 | 初学一级 | 园豆:4
提问于:2013-12-08 20:23
< >
分享
最佳答案
0

2个线程同时进行了,if ((int)money <= _balance) 判断为true了,锁一下

lock(new object())

{

    if ((int)money <= _balance){ do anything....}

}

收获园豆:5
James.Ying | 小虾三级 |园豆:1472 | 2013-12-08 21:25

为避免同时进行,可以再次进行判断

 if ((int)money <= _balance){

    lock(new object()){

     if ((int)money <= _balance){

        do.... 

    }    

}

}

James.Ying | 园豆:1472 (小虾三级) | 2013-12-09 09:43
其他回答(2)
0

没有加锁,同时进入去执行了。lock一下,建议google下多线程的相关文章

Rookier | 园豆:652 (小虾三级) | 2013-12-09 10:39
0

线程没有锁定资源啊。多搜索一下相关的文章和样例。

bitbug | 园豆:470 (菜鸟二级) | 2013-12-09 16:14
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册