using System;
using System.Threading;
namespace P12_8
{
    class Account
    {
        private Object thisLock = new object();
        int balance;
        Random r = new Random();
        public Account(int initial)
        {
            balance = initial;
        }
        int WithDraw(int amount)
        {
            if (balance < 0)
            {
                throw new Exception("Balance.");
            }
            lock (thisLock)
            {
                if (balance >= amount)
                {
                    Console.WriteLine("ǰе߳ǣ" + System.Threading.Thread.CurrentThread.Name + "---------------");

                    Console.WriteLine("Withdrawal֮ǰBalance:" + balance);
                    Console.WriteLine("Amount Withdrawal     :-" + amount);
                    balance = balance - amount;
                    Console.WriteLine("Withdrawal֮Balance :" + balance);
                    return amount;
                }
                else
                {
                    return 0;
                }
            }
        }
        public void DoTransactions()
        {
            for (int i = 0; i < 100; i++)
            {
                WithDraw(r.Next(1, 100));
            }
        }
    }
    class Test
    {
        static void Main(string[] args)
        {
            System.Threading.Thread[] threads = new System.Threading.Thread[10];
            Account acc = new Account(1000);
            for (int i = 0; i < 10; i++)
            {
                System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(acc.DoTransactions));
                threads[i] = t;
                threads[i].Name = "߳" + i.ToString();
            }
            for (int i = 0; i < 10; i++)
            {
                threads[i].Start();
            }
            Console.ReadKey();
        }
    }
}
