猿问

关于线程lock的诡异错误,msdn中的C#编程指南里面的一个范例,程序红色部分为问题

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();
            //}
        }
    }
}

红糖糍粑
浏览 331回答 5
5回答

ABOUTYOU

 i < num ,而 num = 6 num > = 6 时, 退出 for 循环,WithDraw(r.Next(1, 100)); 就不执行了.

婷婷同学_

 我把你的代码运行了一下,没有任何问题,即使把num改成26也没有问题啊,不会出现你说的那种情况,你再试一下,是不是看错了

料青山看我应如是

@码魔谷:CMD不够行输出.你把 Console.WriteLine 改成 Debug.WriteLine,然后从VS的输出窗口中查看结果.

翻阅古今

非常感谢,在输出窗口看到了!
随时随地看视频慕课网APP
我要回答