zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    1022 D进制的A+B
    1021 个位数统计
    L1-040 最佳情侣身高差
    Celery--基本使用
    Celery--安装
    Celery--简介
    RabbitMQ--常用命令
    RabbitMQ--RPC实现
    RabbitMQ发布订阅
    RabbitMQ基本使用
  • 原文地址:https://www.cnblogs.com/Tinamei/p/5162284.html
Copyright © 2011-2022 走看看