您的位置:首页 > 其它

多线程学习Demo注解(2)——lock

2013-09-04 21:27 225 查看
using System;
using System.Threading;

internal class Test3
{
    static internal Thread[] threads = new Thread[10];
    public static void Main()
    {
        Account acc = new Account(0);
        //1. 初始化 10 个线程
        for (int i = 0; i < 10; i++)
        {
            Thread t = new Thread(new ThreadStart(acc.DoTransactions));
            threads[i] = t;
        }
        //2. 给 10 个线程的名字赋值
        for (int i = 0; i < 10; i++)
            threads[i].Name = i.ToString();
        //3. 让 10 个线程都运行起来
        for (int i = 0; i < 10; i++)
            threads[i].Start();
        Console.ReadLine();
    }
}

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

    internal int Withdraw(int amount)
    {
        //这段代码不需要?
        //初始值为0
        //在>=的时候, balance 才发生相减, 不会为负
        //在<的时候, balance 根本就没有经过处理
        if (balance < 0)
        {
            //如果balance小于0则抛出异常
            throw new Exception("Negative Balance");
        }
        //下面的代码保证在当前线程修改balance的值完成之前
        //不会有其他线程也执行这段代码来修改balance的值
        //因此,balance的值是不可能小于0的
        lock (this)
        {
            //如果没有lock关键字的保护,那么可能在执行完if的条件判断之后
            //另外一个线程却执行了balance=balance-amount修改了balance的值
            //而这个修改对这个线程是不可见的,所以可能导致这时if的条件已经不成立了
            //但是,这个线程却继续执行balance=balance-amount,所以导致balance可能小于0
            if (balance >= amount)
            {
                Thread.Sleep(5);
                Console.WriteLine( string.Format("Current Thread:{0} balance: {1} amount: {2} ", Thread.CurrentThread.Name, balance, amount ));
                balance = balance - amount;
                
                return amount;
            }
            else
            {
                Console.WriteLine("Current Thread:" + Thread.CurrentThread.Name + " balance: 0");
                return 0; // transaction rejected
            }
        }
    }
    internal void DoTransactions()
    {
        for (int i = 0; i < 100; i++)
            Withdraw(r.Next(-50, 100));
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: