Lock

Lock理解

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Lock
{
    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("Negative Balance");
            }
            lock (thisLock)
            {
                if(balance >= amount)
                {
                    Console.WriteLine("Balance before Withdrawal: " + balance);
                    Console.WriteLine("Amount to Withdraw  :" + amount);
                    balance -= amount;
                    Console.WriteLine("Balance after Withdrawal: " + balance);
                    return amount;
                }
                else
                {
                    return 0;
                }
            }
        }
        public void DoTransactions()
        {
            for(int i = 0; i < 100; i++)
            {
                Withdraw(r.Next(1, 100));
            }
        }
    }
    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));
                threads[i] = t;
            }
            for(int i = 0; i < 10; i++)
            {
                DateTime s = DateTime.Now;
                threads[i].Start();
                DateTime t = DateTime.Now;
                TimeSpan st = t.Subtract(s);
                Console.WriteLine(st);
            }
            Console.ReadKey();
        }
    }
}
原文地址:https://www.cnblogs.com/Tinamei/p/5162284.html