SingleThreadTester是单线程计数。
1: class SingleThreadTester : ThreadTester 2: { 3: private Stopwatch _aStopWatch = new Stopwatch(); 4: 5: public override void Start() 6: { 7: _aStopWatch.Start(); 8: 9: Thread aThread = new Thread(() => WorkInThread()); 10: aThread.Start(); 11: } 12: 13: public override long GetElapsedMillisecondsOfIncreaseCounter() 14: { 15: return this._aStopWatch.ElapsedMilliseconds; 16: } 17: 18: public override bool IsTesterRunning() 19: { 20: return _aStopWatch.IsRunning; 21: } 22: 23: private void WorkInThread() 24: { 25: while (true) 26: { 27: if (this.GetCounter() > ThreadTester.MAX_COUNTER_NUMBER) 28: { 29: _aStopWatch.Stop(); 30: break; 31: } 32: 33: this.IncreaseCounter(); 34: } 35: } 36: } |
TwoThreadSwitchTester是两个线程交替计数。
1: class TwoThreadSwitchTester : ThreadTester 2: { 3: private Stopwatch _aStopWatch = new Stopwatch(); 4: private AutoResetEvent _autoResetEvent = new AutoResetEvent(false); 5: 6: public override void Start() 7: { 8: _aStopWatch.Start(); 9: 10: Thread aThread1 = new Thread(() => Work1InThread()); 11: aThread1.Start(); 12: 13: Thread aThread2 = new Thread(() => Work2InThread()); 14: aThread2.Start(); 15: } 16: 17: public override long GetElapsedMillisecondsOfIncreaseCounter() 18: { 19: return this._aStopWatch.ElapsedMilliseconds; 20: } 21: 22: public override bool IsTesterRunning() 23: { 24: return _aStopWatch.IsRunning; 25: } 26: 27: private void Work1InThread() 28: { 29: while (true) 30: { 31: _autoResetEvent.WaitOne(); 32: 33: this.IncreaseCounter(); 34: 35: if (this.GetCounter() > ThreadTester.MAX_COUNTER_NUMBER) 36: { 37: _aStopWatch.Stop(); 38: break; 39: } 40: 41: _autoResetEvent.Set(); 42: } 43: } 44: 45: private void Work2InThread() 46: { 47: while (true) 48: { 49: _autoResetEvent.Set(); 50: _autoResetEvent.WaitOne(); 51: this.IncreaseCounter(); 52: 53: if (this.GetCounter() > ThreadTester.MAX_COUNTER_NUMBER) 54: { 55: _aStopWatch.Stop(); 56: break; 57: } 58: } 59: } 60: } |