본문 바로가기

프로그래밍/C#

C# lock

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

using System.Threading.Tasks;



namespace @lock

{

class Account

{

private Object thisLock = new Object();

int balance;



Random r = new Random();



public Account(int initial)

{

balance = initial;

}



int Withdraw(int amount)

{



// This condition never is true unless the lock statement

// is commented out.

if (balance < 0)

{

throw new Exception("Negative Balance");

}



// Comment out the next line to see the effect of leaving out

// the lock keyword.

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 : {0}\n", balance);

return amount;

}

else

{

return 0; // transaction rejected

}

}

}



public void DoTransactions()

{

for (int i = 0; i < 100; i++)

{

Withdraw(r.Next(1, 100));

}

}

}



class Program

{

public void RunMe()

{

Console.WriteLine("RunMe called");

}



static void Main(string[] args)

{

Program b = new Program();

Thread t = new Thread(b.RunMe);

t.Start();



Thread[] threads = new Thread[10];

Account acc = new Account(1000);



for (int i = 0; i < 10; i++)

{

Thread ttttt = new Thread(new ThreadStart(acc.DoTransactions));

threads[i] = ttttt;

}

for (int i = 0; i < 10; i++)

{

threads[i].Start();

}



//block main thread until all other threads have ran to completion.

foreach (var tt in threads)

tt.Join();

}

}

}

반응형

'프로그래밍 > C#' 카테고리의 다른 글

C# 문자열 파싱 parsing split  (0) 2019.03.24
C# 문자열 Mid,Left,Right  (0) 2019.03.24
C# 명령줄 인수  (0) 2019.03.24
C# 비트 연산  (0) 2019.03.24
C# 소켓 클라이언트 socket client  (0) 2019.03.24