码迷,mamicode.com
首页 > 其他好文 > 详细

Lock

时间:2016-01-27 10:48:12      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Lock

标签:

原文地址:http://www.cnblogs.com/Tinamei/p/5162284.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!