首页 > 代码库 > c# 多线程 读写分离

c# 多线程 读写分离

class Program    {        private static ReaderWriterLockSlim _LockSlim = new ReaderWriterLockSlim();        private static Hashtable list = Hashtable.Synchronized(new Hashtable());        static void Main(string[] args)        {            new Thread(new ParameterizedThreadStart(delegate(object obj) {                Write(0, 10000);            })).Start();            Thread.Sleep(1000);            new Thread(new ParameterizedThreadStart(delegate(object obj)            {                Read(1, 1000);            })).Start();            new Thread(new ParameterizedThreadStart(delegate(object obj)            {                Read(2, 1000);            })).Start();            new Thread(new ParameterizedThreadStart(delegate(object obj)            {                Read(3, 1000);            })).Start();            new Thread(new ParameterizedThreadStart(delegate(object obj)            {                Read(4, 1000);            })).Start();            Console.ReadKey();        }        /// <summary>        /// 对于i相同的线程进行阻塞保证不会并行多个        /// </summary>        /// <param name="i"></param>        /// <param name="j"></param>        public static void Read(int i,int j)        {            Console.WriteLine(DateTime.Now.ToString() + "\t线程" + i.ToString() + "即将进入读取状态");            _LockSlim.EnterReadLock();            Console.WriteLine(DateTime.Now.ToString() + "\t线程" + i.ToString() + "进入读取状态");                        Thread.Sleep(j);            _LockSlim.ExitReadLock();            Console.WriteLine(DateTime.Now.ToString() + "\t线程" + i.ToString() + "退出读取状态");        }        public static void Write(int i, int j)        {            Console.WriteLine(DateTime.Now.ToString() + "\t线程" + i.ToString() + "即将进入写入状态");            _LockSlim.EnterWriteLock();            Console.WriteLine(DateTime.Now.ToString() + "\t线程" + i.ToString() + "进入写入状态");            Thread.Sleep(j);            _LockSlim.ExitWriteLock();            Console.WriteLine(DateTime.Now.ToString() + "\t线程" + i.ToString() + "退出写入状态");        }    }

输出:

2017/2/20 17:51:55      线程0即将进入写入状态2017/2/20 17:51:55      线程0进入写入状态2017/2/20 17:51:56      线程1即将进入读取状态2017/2/20 17:51:56      线程2即将进入读取状态2017/2/20 17:51:56      线程3即将进入读取状态2017/2/20 17:51:56      线程4即将进入读取状态2017/2/20 17:52:05      线程1进入读取状态2017/2/20 17:52:05      线程4进入读取状态2017/2/20 17:52:05      线程0退出写入状态2017/2/20 17:52:05      线程2进入读取状态2017/2/20 17:52:05      线程3进入读取状态2017/2/20 17:52:06      线程2退出读取状态2017/2/20 17:52:06      线程1退出读取状态2017/2/20 17:52:06      线程4退出读取状态2017/2/20 17:52:06      线程3退出读取状态

 

c# 多线程 读写分离