Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; <br/> using system. threading; </P> <p> namespace multithreading <br/>{< br/> class synchronization mode <br/>{< br/> Public static void main () <br/>{< br/> // There is nothing worth noting about the sequence call of non-synchronous versions <br/> // demo d = new demo (); <br/> // console. writeline ("synchronous?" + D. issynchronized); <br/> // D. dothat (); <br/> // D. dothis (); </P> <p> // below we use two threads Execute two methods respectively. (Version not synchronized) <br/> // you can see from the result that the data is executed alternately (for convenience, data is not shared here) <br/> // demo d = new demo (); </P> <p> // thread T1 = new thread (D. dothis); <br/> // t1.name = "thread 1"; <br/> // t1.start (); </P> <p> // thread t2 = new thread (D. dothat); <br/> // t2.name = "thread 2"; <br/> // t2.start (); </P> <p> // use the synchronization version for example, the result shows that after thread 1 is executed, thread 2 has the right to execute <br/> demo d = new demo (); <br/> d = demo. synchronized (d); </P> <p> thread T1 = new thread (D. dothis); <br/> T1.name = "thread 1"; <br/> t1.start (); </P> <p> thread t2 = new thread (D. dothat); <br/> t2.name = "thread 2"; <br/> t2.start (); </P> <p> console. readline (); <br/>}</P> <p> class demo <br/>{< br/> Public Virtual bool issynchronized <br/> {<br/> get {return false ;} <br/>}</P> <p> Public Virtual void dothis () <br/>{< br/> console. writeline ("doing these things"); </P> <p> for (INT I = 0; I <150; I ++) <br/> {<br/> Console. writeline ("this" + I. tostring (); <br/>}</P> <p> Public Virtual void dothat () <br/>{< br/> console. writeline ("something done"); </P> <p> for (INT I = 0; I <150; I ++) <br/> {<br/> console. writeline ("that" + I. tostring (); <br/>}</P> <p> Public static demo synchronized (Demo D) <br/>{< br/> If (! D. issynchronized) <br/>{< br/> return New syncdemo (d); <br/>}</P> <p> return D; <br/>}</P> <p> // <summary> <br/> // internal class, returns the demo object of the synchronous version <br/> /// </Summary> <br/> private class syncdemo: Demo <br/>{< br/> private demo D; <br/> private object sync = new object (); </P> <p> Public syncdemo (Demo d) <br/>{< br/> This. D = D; <br/>}</P> <p> Public override void dothat () <br/>{< br/> lock (Sync) <br/>{< br/> base. dothat (); <br/>}</P> <p> Public override void dothis () <br/>{< br/> lock (Sync) <br/>{< br/> base. dothis (); <br/>}</P> <p> Public override bool issynchronized <br/>{< br/> Get <br/>{< br/> return true; <br/>}</P> <p>}