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

📄 sharedintegersynchronized.cs

📁 北大青鸟内部资料
💻 CS
字号:
using System;
using System.Threading;
namespace Multithreading
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	public class SharedIntegerSynchronized
	{
		// buffer shared by producer and consumer threads 
		private int buffer = -1;
		int bufferCopy;
		// _occupiedBufferCount maintains count of occupied buffers
		private int _occupiedBufferCount = 0;  

		// property Buffer
		public int Buffer
		{      
			
			get
			{ 
				// obtain lock on this object
				//Console.Write(Thread.CurrentThread.Name.ToString());
				lock(this)
				{
					// if there is no data to read, place invoking 
					if ( _occupiedBufferCount == 0 )
					{
						Console.WriteLine( 
							Thread.CurrentThread.Name + " 尝试读取。" );

						DisplayState( "缓冲区为空。" + 
							Thread.CurrentThread.Name + " 等待。" );

					}

					// indicate that consumer can retrieve another buffer value 
					else if ( _occupiedBufferCount == 1 )
					{
						//prodcer can store another value 
						// buffer is empty
						--_occupiedBufferCount;    
	                                 
						DisplayState( 
							Thread.CurrentThread.Name + " 读取 " + buffer );

						// Get copy of buffer before releasing lock. 
						// It is possible that the producer could be
						// assigned the processor immediately after the
						// monitor is released and before the return 
						// statement executes. In this case, the producer 
						// would assign a new value to buffer before the 
						// return statement returns the value to the 
						// consumer. Thus, the consumer would receive the 
						// new value. Making a copy of buffer and 
						// returning the copy ensures that the
						// consumer receives the proper value.
						bufferCopy = buffer;
						
					}
					return bufferCopy;
				}
			} // end get

			set
			{
				// acquire lock for this object
				lock(this)
				{

					// if there are no empty locations, place invoking
					if ( _occupiedBufferCount == 1 )
					{
						Console.WriteLine( 
							Thread.CurrentThread.Name + " 尝试写入。" );

						DisplayState( "缓冲区为满。" + 
							Thread.CurrentThread.Name + " 等待。" );

					}

					// set new sharedInt value
					else
					{
						buffer = value;

						// indicate producer cannot store another value 
						// until consumer retrieves current sharedInt value
						++_occupiedBufferCount;

						DisplayState( 
							Thread.CurrentThread.Name + " 写入 " + buffer );
					}
					
				}

			} // end set

		} // end property Buffer

		// display current operation and buffer state
		public void DisplayState( string operation )
		{
			Console.WriteLine( "{0,-35}{1,-9}{2}\n", 
				operation, buffer, _occupiedBufferCount );
		}

	} // end class SharedIntegerSynchronized
}

⌨️ 快捷键说明

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