using System;<br />using System.Collections.Generic;<br />using System.Text;<br />using System.Threading;<br />public class CRunMain<br />{<br /> public static void Main()<br /> {<br /> CTest test = new CTest(1000);<br /> Thread trd1 = new Thread(new ThreadStart(test.Add));<br /> Thread trd2 = new Thread(new ThreadStart(test.Delete));<br /> trd1.Start();<br /> trd2.Start();<br /> while (true)<br /> {<br /> Console.WriteLine("===================== main thread is running ===================");<br /> Thread.Sleep(100);<br /> }<br /> }<br />}<br />public class CTest<br />{<br /> private object objLock = new object();<br /> private int m_nCount = 100;<br /> public CTest(int nVal)<br /> {<br /> m_nCount = nVal;<br /> }<br /> public void Add()<br /> {<br /> while (true)<br /> {<br /> lock(objLock)<br /> {<br /> m_nCount += 1;<br /> Console.WriteLine("after add 1" + "/tnCount = " + m_nCount);<br /> }<br /> if (this.m_nCount > 0)<br /> {<br /> Thread.Sleep(10);<br /> }<br /> }<br /> }<br /> public void Delete()<br /> {<br /> while (true)<br /> {<br /> lock (objLock)<br /> {<br /> m_nCount -= 1;<br /> Console.WriteLine("after sub 1" + "/tnCount = " + m_nCount);<br /> }<br /> if (this.m_nCount < 0)<br /> {<br /> Thread.Sleep(10);<br /> }<br /> }<br /> }<br />}