Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Threading;
- namespace Deadlock
- {
- internal class Program
- {
- private static void Main(string[] args)
- {
- Console.WriteLine("Main Started");
- Account accountA = new Account(101, 5000);
- Account accountB = new Account(101, 3000);
- var accountManagerA = new AccountManager(accountA, accountB, 1000);
- var t1 = new Thread(accountManagerA.Transfer);
- t1.Name = "#1 Thread";
- var accountManagerB = new AccountManager(accountB, accountA, 2000);
- var t2 = new Thread(accountManagerB.Transfer);
- t2.Name = "#2 Thread";
- t1.Start();
- t2.Start();
- t1.Join();
- t2.Join();
- Console.WriteLine("Main Completed");
- }
- }
- internal class Account
- {
- private double _balance; private int _id;
- public int ID { get { return _id; } }
- public Account(int id, int balance)
- {
- // TODO: Complete member initialization
- this._id = id;
- this._balance = balance;
- }
- public void WitdhDraw(double amount)
- {
- _balance -= amount;
- }
- public void Deposit(double amount)
- {
- _balance += amount;
- }
- }
- internal class AccountManager
- {
- private Account _fromAccount;
- private Account _toAccount;
- private int _amountToTransfer;
- public AccountManager(Account fromAccount, Account toAccount, int amountToTransfer)
- {
- this._fromAccount = fromAccount;
- this._toAccount = toAccount;
- this._amountToTransfer = amountToTransfer;
- }
- public void Transfer()
- {
- lock (_fromAccount)
- {
- Thread.Sleep(1000);
- lock (_toAccount)
- {
- _fromAccount.WitdhDraw(_amountToTransfer);
- _toAccount.Deposit(_amountToTransfer);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement