static void Ex11() { //in our scenario we have a Bank that //can Transfer an amount from a source BankAccount //to a target BankAccount. //if we do not use multithreading, //no problems will arise ExampleLibrary.BankScenario.BankAccount ba1 = new ExampleLibrary.BankScenario.BankAccount() { Id = 1 }; ExampleLibrary.BankScenario.BankAccount ba2 = new ExampleLibrary.BankScenario.BankAccount() { Id = 2 }; ba1.Deposit(100); ExampleLibrary.BankScenario.NotSynchronized.Bank bank = new ExampleLibrary.BankScenario.NotSynchronized.Bank(); for (int i = 0; i < 100; i++) //200 transfer { bank.Transfer(ba1, ba2, 50); bank.Transfer(ba2, ba1, 50); } Console.WriteLine($"{ba1.Id} == {ba1.Saldo}\t{ba2.Id} == {ba2.Saldo}"); //ba1.Saldo == 100, ba2.Saldo == 0 }
static void Ex12() { //same Bank that //can Transfer an amount from a source BankAccount //to a target BankAccount. //if multiple threads try to transfer from the same //accounts, concurrency problems could arise.... ExampleLibrary.BankScenario.BankAccount ba1 = new ExampleLibrary.BankScenario.BankAccount() { Id = 1 }; ExampleLibrary.BankScenario.BankAccount ba2 = new ExampleLibrary.BankScenario.BankAccount() { Id = 2 }; ba1.Deposit(100); ExampleLibrary.BankScenario.NotSynchronized.Bank bank = new ExampleLibrary.BankScenario.NotSynchronized.Bank(); for (int i = 0; i < 100; i++) //200 concurrent Threads running transfer { new Thread(() => { bank.Transfer(ba1, ba2, 50); Console.WriteLine($"{ba1.Id} == {ba1.Saldo}\t{ba2.Id} == {ba2.Saldo}"); }).Start(); new Thread(() => { bank.Transfer(ba2, ba1, 50); Console.WriteLine($"{ba1.Id} == {ba1.Saldo}\t{ba2.Id} == {ba2.Saldo}"); }).Start(); } //we could see weird numbers popping up.... }