public class C { static private ReaderWriterLockSlim rwl = new ReaderWriterLockSlim(); public static void Main() { Thread t_read1 = new Thread(new ThreadStart(WriteSomething)); t_read1.Start(); Console.WriteLine("{0} Create Thread ID {1} , Start WriteSomething", DateTime.Now.ToString("hh:mm:ss fff"), t_read1.GetHashCode()); Thread t_read2 = new Thread(new ThreadStart(WriteSomething)); t_read2.Start(); Console.WriteLine("{0} Create Thread ID {1} , Start WriteSomething ", DateTime.Now.ToString("hh:mm:ss fff"), t_read2.GetHashCode()); Thread t_write1 = new Thread(new ThreadStart(ReadSomething)); t_write1.Start(); Console.WriteLine("{0} Create Thread ID {1} , Start ReadSomething", DateTime.Now.ToString("hh:mm:ss fff"), t_write1.GetHashCode()); Thread t_write2 = new Thread(new ThreadStart(ReadSomething)); t_write2.Start(); Console.WriteLine("{0} Create Thread ID {1} , Start ReadSomething", DateTime.Now.ToString("hh:mm:ss fff"), t_write2.GetHashCode()); } static public void ReadSomething() { Console.WriteLine("{0} Thread ID {1} Begin EnterReadLock...", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode()); rwl.EnterReadLock(); try { Console.WriteLine("{0} Thread ID {1} reading sth...", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode()); Thread.Sleep(5000);//模拟读取信息 Console.WriteLine("{0} Thread ID {1} reading end.", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode()); } finally { rwl.ExitReadLock(); Console.WriteLine("{0} Thread ID {1} ExitReadLock...", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode()); } } static public void WriteSomething() { Console.WriteLine("{0} Thread ID {1} Begin EnterWriteLock...", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode()); rwl.EnterWriteLock(); try { Console.WriteLine("{0} Thread ID {1} writing sth...", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode()); Thread.Sleep(10000);//模拟写入信息 Console.WriteLine("{0} Thread ID {1} writing end.", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode()); } finally { rwl.ExitWriteLock(); Console.WriteLine("{0} Thread ID {1} ExitWriteLock...", DateTime.Now.ToString("hh:mm:ss fff"), Thread.CurrentThread.GetHashCode()); } } }
可以同时读取数据,但只能一个线程进入写数据。
标签:Console,Thread,记录,c#,读写,DateTime,WriteLine,GetHashCode,fff From: https://www.cnblogs.com/Insist-Y/p/17434291.html