C#线程同步模式

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace 多线程 { class 同步模式 { public static void Main() { //对于不同步版本的顺序调用,没什么值得说明的 //Demo d = new Demo() ; //Console.WriteLine( "是不是同步" + d.IsSynchronized ) ; //d.DoThat() ; //d.DoThis() ; //下面我们用2条线程来分别执行2个方法。(不同步版本) //从结果可以看出,交替执行(为了方便,这里不再共享数据) //Demo d = new Demo() ; //Thread t1 = new Thread( d.DoThis ) ; //t1.Name = "线程1" ; //t1.Start() ; //Thread t2 = new Thread(d.DoThat); //t2.Name = "线程2"; //t2.Start(); //例用同步版本,结果中看出,线程1执行完后,线程二才有权利执行 Demo d = new Demo(); d = Demo.Synchronized(d); Thread t1 = new Thread(d.DoThis); t1.Name = "线程1"; t1.Start(); Thread t2 = new Thread(d.DoThat); t2.Name = "线程2"; t2.Start(); Console.ReadLine(); } } class Demo { public virtual bool IsSynchronized { get { return false; } } public virtual void DoThis() { Console.WriteLine("做了这些事情"); for (int i = 0; i < 150; i++) { Console.WriteLine("This " + i.ToString()); } } public virtual void DoThat() { Console.WriteLine("做了那些事"); for (int i = 0; i < 150; i++) { Console.WriteLine("That " + i.ToString()); } } public static Demo Synchronized(Demo d) { if (!d.IsSynchronized) { return new SyncDemo(d); } return d; } /// <summary> /// 内部类,用来返回同步版的Demo对象 /// </summary> private class SyncDemo : Demo { private Demo d; private object sync = new object(); public SyncDemo(Demo d) { this.d = d; } public override void DoThat() { lock (sync) { base.DoThat(); } } public override void DoThis() { lock (sync) { base.DoThis(); } } public override bool IsSynchronized { get { return true; } } } } }

你可能感兴趣的:(thread,多线程,object,C#,Class)