关闭

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

标签: 多线程c#threadrandomexceptionclass
607人阅读 评论(0) 收藏 举报

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

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:201687次
    • 积分:2802
    • 等级:
    • 排名:第12786名
    • 原创:71篇
    • 转载:17篇
    • 译文:24篇
    • 评论:9条
    最新评论