多线程学习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)); } }
相关文章推荐
- 多线程学习Demo注解(3)——生产者和消费者
- 多线程学习Demo注解(1)
- Java学习--多线程之Lock的使用
- 多线程程序设计学习(7)read-write lock pattern
- java多线程学习之ReentrantReadWriteLock(二)
- JAVA学习笔记_demo_多线程_1
- java自定义注解学习(一)_demo小练习
- 多线程基础学习十四:ReadWriteLock与ReentrantReadWriteLock
- java学习笔记之多线程的锁接口Lock
- java 多线程学习之多生产者多消费者产生的线程安全问题分析与解决:Lock和Condition
- JAVA多线程学习之ReentrantReadWriteLock
- java多线程学习之ReentrantLock
- 多线程生产者消费者Demo2_ Lock操作
- Spring学习笔记-springMVC基于注解的控制器(Demo)
- 【Java学习笔记】58:多线程Socket通信的demo
- lombok最全的,最新的学习资料,demo【最全的注解】打开蓝色注解链接
- 多线程学习三(synchronized和Lock)
- C#多线程学习(九)lock,Monitor,Mutex的区别
- java多线程学习8-显示锁Lock和ReentrantLock
- java多线程学习笔记——concurrent包的一些类(Lock 和Condition)