1.多线程中有个共享概念,如果多个线程同时对一个对象都有操作权限,就会出现竞争的情况,这样也造成改对象的不稳定性。
2.对于共享造成的数据紊乱,有个根本的解决办法,就是不一定通过共享方案解决一个问题,可以重新设计代码结构,移除共享方案。
共享数据的同步方案整理:
1.lock
在多线程中使用lock一个对象,lock易造成死锁,设计需谨慎。
为多个线程共享的变量提供原子操作。相比lock的好处不会出现死锁。
3.AutoResetEvent
新实例初始化 AutoResetEvent 使用 Boolean 值,该值指示是否将初始状态设置为终止状态的类。
private static AutoResetEvent workerEvent = new AutoResetEvent(false);
private static AutoResetEvent mainEvent = new AutoResetEvent(false);
static void Process(int seconds)
{
Console.WriteLine("Starting a long running work....");
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine("Work is done");
workerEvent.Set();//步骤2
Console.WriteLine("Waiting for a main thread to complete its work");
mainEvent.WaitOne();//步骤3
Console.WriteLine("Starting second operation...");
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine("Work is done!");
workerEvent.Set();//步骤6
}
static void Main(string[] args)
{
var t = new Thread(()=>Process(10));
t.Start();
Console.WriteLine("Waiting for another thread to complete work");
workerEvent.WaitOne();//步骤1
Console.WriteLine("First operation is complete");
Console.WriteLine("Perfoming an operation on a main thread");
Thread.Sleep(TimeSpan.FromSeconds(5));
mainEvent.Set();//步骤4
Console.WriteLine("Now running the second operation on a second thread");
workerEvent.WaitOne();//步骤5
Console.WriteLine("Second operation is completed");
//Console.ReadKey();
}