using System; using System.Collections; using System.Text; using System.Threading; public class CRunMain { public static void Main() { //SyncThread1(); //SyncThread2(); SyncThread3(); } public static void SyncThread1() { CTest test = new CTest(1000); Thread trd1 = new Thread(new ThreadStart(test.Add)); Thread trd2 = new Thread(new ThreadStart(test.Sub)); trd1.Start(); trd2.Start(); while (true) { Console.WriteLine("===================== main thread is running ==================="); Thread.Sleep(100); } } public static void SyncThread2() { CTest2 test = new CTest2(100); Thread trd1 = new Thread(new ThreadStart(test.Add)); Thread trd2 = new Thread(new ThreadStart(test.Sub)); trd1.Start(); trd2.Start(); while (true) { Console.WriteLine("===================== main thread is running ==================="); Thread.Sleep(100); } } public static void SyncThread3() { CTest3 test = new CTest3(10); Thread trd1 = new Thread(new ThreadStart(test.Add)); Thread trd2 = new Thread(new ThreadStart(test.Sub)); trd1.Start(); trd2.Start(); while (true) { Console.WriteLine("===================== main thread is running ==================="); Thread.Sleep(1000); } } } public class CTest3 { private Mutex m_objMutex; private int m_nCount = 0; public CTest3(int nVal) { m_objMutex = new Mutex(); m_nCount = nVal; } public void Add() { while (true) { m_objMutex.WaitOne(); m_nCount += 1; Console.WriteLine("after add 1" + "\tnCount = " + m_nCount); m_objMutex.ReleaseMutex(); if (m_nCount > 0) { Thread.Sleep(1000); } } } public void Sub() { while (true) { m_objMutex.WaitOne(); m_nCount -= 1; Console.WriteLine("after sub 1" + "\tnCount = " + m_nCount); m_objMutex.ReleaseMutex(); if (m_nCount < 0) { Thread.Sleep(1000); } } } } public class CTest2 { private object m_objLock = new object(); private int m_nCount = 0; public CTest2(int nVal) { m_nCount = nVal; } public void Add() { while (true) { Monitor.Enter(m_objLock); m_nCount += 1; Console.WriteLine("after add 1" + "\tnCount = " + m_nCount); Monitor.Exit(m_objLock); if (m_nCount > 0) { Thread.Sleep(100); } } } public void Sub() { while (true) { Monitor.Enter(m_objLock); m_nCount -= 1; Console.WriteLine("after sub 1" + "\tnCount = " + m_nCount); Monitor.Exit(m_objLock); if (m_nCount < 0) { Thread.Sleep(100); } } } } public class CTest { private object objLock = new object(); private int m_nCount = 100; public CTest(int nVal) { m_nCount = nVal; } public void Add() { while (true) { lock(objLock) { m_nCount += 1; Console.WriteLine("after add 1" + "\tnCount = " + m_nCount); } if (this.m_nCount > 0) { Thread.Sleep(10); } } } public void Sub() { while (true) { lock (objLock) { m_nCount -= 1; Console.WriteLine("after sub 1" + "\tnCount = " + m_nCount); } if (this.m_nCount < 0) { Thread.Sleep(10); } } } }
C#多线程源代码实例包含lock, Monitor, mutex
最新推荐文章于 2022-06-29 09:16:35 发布