理解c#多线程中的lock关键字

来源:互联网 发布:手机家庭监控器软件 编辑:程序博客网 时间:2024/09/21 11:23

using System;
using System.Threading;

internal class Account
{
    int balance;
    Random r = new Random();
    internal Account(int initial)
    {
        balance = initial;
    }

    internal int Withdraw(int amount)
    {
        if (balance < 0)
        {
            throw new Exception("Negative Balance");
        }

        lock (this)
        {
            Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name);

            if (balance >= amount)
            {
                Thread.Sleep(50);
                balance = balance - amount;
                return amount;
            }
            else
            {
                return 0;
            }
        }
    }
    internal void DoTransactions()
    {
        for (int i = 0; i < 100; i++)
            Withdraw(r.Next(-50, 100));
    }
}

internal class Test
{
    static internal Thread[] threads = new Thread[10];
    public static void Main()
    {
        Account acc = new Account(0);
        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++)
            threads[i].Name = i.ToString();
        for (int i = 0; i < 10; i++)
            threads[i].Start();
        Console.ReadLine();
    }
}

原创粉丝点击