zoukankan      html  css  js  c++  java
  • C#的lock语句

    文章:lock 语句(C# 参考)

    代码:

    using System;
    using System.Threading.Tasks;
    
    public class Account
    {
        private readonly object balanceLock = new object();
        private decimal balance;
    
        public Account(decimal initialBalance)
        {
            balance = initialBalance;
        }
    
        public decimal Debit(decimal amount)
        {
            lock (balanceLock)
            {
                if (balance >= amount)
                {
                    Console.WriteLine($"Balance before debit :{balance, 5}");
                    Console.WriteLine($"Amount to remove     :{amount, 5}");
                    balance = balance - amount;
                    Console.WriteLine($"Balance after debit  :{balance, 5}");
                    return amount;
                }
                else
                {
                    return 0;
                }
            }
        }
    
        public void Credit(decimal amount)
        {
            lock (balanceLock)
            {
                Console.WriteLine($"Balance before credit:{balance, 5}");
                Console.WriteLine($"Amount to add        :{amount, 5}");
                balance = balance + amount;
                Console.WriteLine($"Balance after credit :{balance, 5}");
            }
        }
    }
    
    class AccountTest
    {
        static void Main()
        {
            var account = new Account(1000);
            var tasks = new Task[100];
            for (int i = 0; i < tasks.Length; i++)
            {
                tasks[i] = Task.Run(() => RandomlyUpdate(account));
            }
            Task.WaitAll(tasks);
        }
    
        static void RandomlyUpdate(Account account)
        {
            var rnd = new Random();
            for (int i = 0; i < 10; i++)
            {
                var amount = rnd.Next(1, 100);
                bool doCredit = rnd.NextDouble() < 0.5;
                if (doCredit)
                {
                    account.Credit(amount);
                }
                else
                {
                    account.Debit(amount);
                }
            }
        }
    }

    演示了lock语句的使用。

  • 相关阅读:
    文件上传和下载
    代理模式
    设计模式分类
    单例模式
    抽象工厂模式
    成长
    Java教程
    python面试大全
    python入门教程
    收藏网摘
  • 原文地址:https://www.cnblogs.com/Tpf386/p/9987704.html
Copyright © 2011-2022 走看看