/* * 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() { while (!_flag)// if flag == false, enter loop-waiting ; Console.WriteLine("Consumer: {0}", _resourceContent); // set _flag to be false, it means that consuming finished. _flag = false; } /// <summary> /// puroduce method /// </summary> public void Produce() { // if _flag == true, enter loop-waiting while (_flag) ; ++_resourceContent; Console.WriteLine("Producer: {0}", _resourceContent); _flag = true;// produce finished } } }
时间: 2024-12-30 23:49:58