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;
bool lockedCount = false;
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)
{
lock(thisLock)
{
while(count < 0 || lockedCount == true)
{
Monitor.Wait(thisLock);
lockedCount = true;
count ++;
lockedCount = false;
Monitor.Pulse(thisLock);
}
}
}
}
public void Decrease()
{
int loopCount = LOOP_COUNT;
while (loopCount-- > 0)
{
lock (thisLock)
{
while (count < 0 || lockedCount == true)
{
Monitor.Wait(thisLock);
lockedCount = true;
count++;
lockedCount = false;
Monitor.Pulse(thisLock);
}
}
}
}
}
}
728x90
'C# > 책 예제' 카테고리의 다른 글
C# Task Task<TResult> 클래스 사용하기. (0) | 2019.06.08 |
---|---|
C# Task Task 클래스 사용하기. (0) | 2019.06.08 |
C# Thread Monitor 키워드를 이용한 동기화 (0) | 2019.06.08 |
C# Thread lock 키워드를 이용한 동기화 (0) | 2019.06.08 |
C# Thread 인터럽트로 종료하기. (0) | 2019.06.08 |
댓글