⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sample50.cs

📁 C#函数手册
💻 CS
字号:
namespace apiBook
{
	using System;
	using System.Threading;
	using System.Collections; 
	public class TestMonitorClass
	{
		Queue   testQ=new Queue();
		const int MAX = 10;			
		static int counter=0;		
		public static void Main()
		{			
			TestMonitorClass t = new TestMonitorClass();         			
			Thread t1 = new Thread(new ThreadStart(t.FirstThread));			
			Thread t2= new Thread(new ThreadStart(t.SecondThread));
			t1.Start();
			t2.Start();
			t1.Join();
			t2.Join();      
			Console.WriteLine("Queue对象的元素现在个数:"+t.GetQueueLength());
			Console.ReadLine();
		}
		public void FirstThread()
		{
			Monitor.Enter(testQ);
		{		
			while(counter < MAX)
			{
				Monitor.Wait(testQ);
				//使用Wait方法
				if(Monitor.TryEnter(testQ))Monitor.Enter(testQ);
				Console.WriteLine("FirstThread线程添加元素"+counter);					   
				testQ.Enqueue(counter);
				counter++;
				Monitor.Exit(testQ);
				//使用Exit方法
				Monitor.Pulse(testQ);  
				//使用Pulse方法 					
			}  				
		}						
			Monitor.Wait(testQ);
			Monitor.Exit(testQ);
		}
		public void SecondThread()
		{
			Monitor.Enter(testQ);
			//使用Enter方法
		{				
			Monitor.Pulse(testQ);
			while(Monitor.Wait(testQ))
			{
				if(Monitor.TryEnter(testQ))Monitor.Enter(testQ);		
				Console.Write("SecondThread读取元素");
				object c=testQ.Dequeue();
				Console.Write("c="+c.ToString());
				Console.WriteLine();
				Monitor.Exit(testQ);
				Monitor.Pulse(testQ);	
			}	
			Monitor.Exit(testQ);
		}
		}				
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -