/* * Created by SharpDevelop. * User: huangyibiao * Date: 2013/8/27 * Time: 11:12 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Threading; namespace ThreadTest { class Program { public static void Main(string[] args) { // create share resource Resource sharedResource = new Resource(); ProduceThread produceThread = new ProduceThread(sharedResource); ConsumeThread consumeThread = new ConsumeThread(sharedResource); // create two thread Thread producer = new Thread(new ThreadStart(produceThread.Run)); Thread consumer = new Thread(new ThreadStart(consumeThread.Run)); try { producer.Start(); consumer.Start(); producer.Join(); consumer.Join(); } catch (ThreadStateException e) { Console.WriteLine(e.ToString()); } Console.ReadKey(); } } public class ProduceThread { /// <summary> /// share resource /// </summary> Resource _resource; public ProduceThread(Resource res) { _resource = res; } // begin to produce public void Run() { for (int i = 0; i < 10; ++i) { _resource.Produce(); } } } public class ConsumeThread { /// <summary> /// share resource /// </summary> Resource _resource; public ConsumeThread(Resource res) { _resource = res; } public void Run() { for (int i = 0; i < 10; ++i) { _resource.Consume(); } } } public class Resource { int _resourceContent = 0; bool _flag = false; /// <summary> /// consume method /// </summary> public void Consume() { // get access power Monitor.Enter(this); // if this object has been locked by other thread, then wait. if (!_flag) { try { Monitor.Wait(this); } catch (SynchronizationLockException e) { Console.WriteLine(e); } catch (ThreadInterruptedException e) { Console.WriteLine(e); } } // show contents after getting the access power Console.WriteLine("Consumer: {0}", _resourceContent); _flag = false; Monitor.Pulse(this);// tell the waiting thread, Consume method has finished Monitor.Exit(this); // exit the synchronization } /// <summary> /// puroduce method /// </summary> public void Produce() { // get access power Monitor.Enter(this); // if this object has been locked by other thread, then wait. if (_flag) { try { Monitor.Wait(this); } catch (SynchronizationLockException e) { Console.WriteLine(e); } catch (ThreadInterruptedException e) { Console.WriteLine(e); } } // show contents after getting the access power Console.WriteLine("Consumer: {0}", ++_resourceContent); _flag = true; Monitor.Pulse(this);// tell the waiting thread, Consume method has finished Monitor.Exit(this); // exit the synchronization } } }
时间: 2024-09-19 21:06:51