C#多线程编程(2):线程的同步
2010-09-30 21:09:36 来源:WEB开发网手控同步是指使用不同的同步类来创建自己的同步机制。使用这种策略要求手动地为不同的域或者方法同步。
ReaderWriterLock
ReaderWriterLock支持单个写线程和多个读线程的锁。在任一特定时刻允许多个线程同时进行读操作或者一个线程进行写操作,使用ReaderWriterLock来进行读写同步比使用监视的方式(如Monitor)效率要高。
下面是一个例子,在例子中使用了两个读线程和一个写线程,代码如下:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace StartThread
{
public class ReadWriteLockDemo
{
private int number;
private ReaderWriterLock rwl;
private Random random;
public ReadWriteLockDemo()
{
rwl = new ReaderWriterLock();
random = new Random();
}
/// <summary>
/// 读线程要执行的方法
/// </summary>
public void Read()
{
Thread.Sleep(10);//暂停,确保写线程优先执行
for (int i = 0; i < 5; i++)
{
rwl.AcquireReaderLock(Timeout.Infinite);
Console.WriteLine("Thread" + Thread.CurrentThread.GetHashCode() + "读出数据,number=" + number);
Thread.Sleep(500);
rwl.ReleaseReaderLock();
}
}
/// <summary>
/// 写线程要执行的方法
/// </summary>
public void Write()
{
for (int i = 0; i < 5; i++)
{
rwl.AcquireWriterLock(Timeout.Infinite);
number = random.Next(DateTime.Now.Millisecond);
Thread.Sleep(100);
Console.WriteLine("Thread" + Thread.CurrentThread.GetHashCode() + "写入数据,number=" + number);
rwl.ReleaseWriterLock();
}
}
public static void Main()
{
ReadWriteLockDemo rwld=new ReadWriteLockDemo();
Thread reader1 = new Thread(new ThreadStart(rwld.Read));
Thread reader2 = new Thread(new ThreadStart(rwld.Read));
reader1.Start();
reader2.Start();
Thread writer1 = new Thread(new ThreadStart(rwld.Write));
writer1.Start();
Console.ReadLine();
}
}
}
更多精彩
赞助商链接