lock

    class Program
    {
        static void Main(string[] args)
        {
            Thread[] threads = new Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                Thread t = new Thread(new ThreadStart(acc.DoTransactions));
                t.Name = "Thread" + i;
                threads[i] = t;
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }
            Console.ReadKey();
        }
    }
    class Account
    {
        private Object thisLock = new Object();
        int balance;
        Random r = new Random();

        public Account(int initial)
        {
            balance = initial;
        }

        int Withdraw(int amount)
        {
            // This condition will never be true unless the lock statement
            // is commented out:
            if (balance < 0)
            {
                throw new Exception("Negative Balance");
            }

            // Comment out the next line to see the effect of leaving out 
            // the lock keyword:
            lock (thisLock)
            {
                if (balance >= amount)
                {
                    Console.WriteLine(Thread.CurrentThread.Name + ":,扣款前金额:" + balance);
                    Console.WriteLine("扣款金额:" + amount);
                    balance = balance - amount;
                    Console.WriteLine("-------扣款后金额:" + balance);
                    return amount;
                }
                else
                {
                    return 0; // transaction rejected
                }
            }
        }

        public void DoTransactions()
        {
            for (int i = 0; i < 1000; i++)
            {
                Withdraw(r.Next(1, 10));
            }
        }
    }
View Code

 

posted @ 2015-10-21 09:29  Albertjoey  阅读(98)  评论(0编辑  收藏  举报