using System;
using System.Threading;
namespace ThreadNTask
{
class Program
{
static void Main(string[] args)
{
Counter counter = new Counter();
Thread increaseThread = new Thread(new ThreadStart(counter.Increase));
Thread decreaseThread = new Thread(new ThreadStart(counter.Decrease));
increaseThread.Start();
decreaseThread.Start();
increaseThread.Join();
decreaseThread.Join();
Console.WriteLine(counter.Count);
}
}
class Counter
{
const int LOOP_COUNT = 1000;
readonly object thisLock;
private int count;
public int Count
{
get{ return count; }
}
public Counter()
{
thisLock = new object();
count = 0;
}
public void Increase()
{
int loopCount = LOOP_COUNT;
while(loopCount-- > 0)
{
Monitor.Enter(thisLock);
try
{
count++;
}
finally
{
Monitor.Exit(thisLock);
}
Thread.Sleep(1);
}
}
public void Decrease()
{
int loopCount = LOOP_COUNT;
while (loopCount-- > 0)
{
Monitor.Enter(thisLock);
try
{
count--;
}
finally
{
Monitor.Exit(thisLock);
}
Thread.Sleep(1);
}
}
}
}
728x90
'C# > 책 예제' 카테고리의 다른 글
C# Task Task 클래스 사용하기. (0) | 2019.06.08 |
---|---|
C# Thread Monitor.Wait 그리고 Monitor.Pulse 사용하기 (0) | 2019.06.08 |
C# Thread lock 키워드를 이용한 동기화 (0) | 2019.06.08 |
C# Thread 인터럽트로 종료하기. (0) | 2019.06.08 |
C# Thread 상태 변화 (0) | 2019.06.08 |
댓글