// using System.Threading; class Account { private Object thisLock = new Object(); int balance; Random r = new Random(); public Account(int initial) { balance = initial; } int Withdraw(int amount) { // Состояние никогда не будет true пока работает lock if (balance < 0) { throw new Exception("Negative Balance"); } // Закомментируем следующую строку и смотрим что будет lock (thisLock) { if (balance >= amount) { Console.WriteLine("Balance before Withdrawal : " + balance); Console.WriteLine("Amount to Withdraw : -" + amount); balance = balance - amount; Console.WriteLine("Balance after Withdrawal : " + balance); return amount; } else { return 0; // транзакция отклонена } } } public void DoTransactions() { for (int i = 0; i < 100; i++) { Withdraw(r.Next(1, 100)); } } } class Test { static void Main() { Thread[] threads = new Thread[10]; Account acc = new Account(1000); 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].Start(); } } }
Ярлыки
.htaccess
(4)
тестирование
(8)
шаблоны проектирования
(3)
css
(5)
Debian
(6)
docker
(2)
Doctrine2
(6)
Git
(6)
html
(4)
java
(6)
javascript
(13)
jquery
(11)
LFS
(3)
linux
(23)
mac os
(4)
mod_rewrite
(2)
MSSQL
(4)
MySQL
(18)
ORM Doctrine
(17)
patterns
(3)
PDO
(3)
perl
(7)
PHP
(64)
PHPUnit
(8)
Python
(15)
SEO
(2)
Silex
(1)
SimpleXML
(1)
SQL
(14)
ssh
(4)
Ubuntu
(24)
Yii1
(1)
Zend Framework
(19)
ZendFramework2
(8)
среда, 6 апреля 2011 г.
C#. Блокировка важной части кода (lock).
Подписаться на:
Комментарии к сообщению (Atom)
Комментариев нет:
Отправить комментарий