Using system; <br/> using system. collections. generic; <br/> using system. LINQ; <br/> using system. text; <br/> using system. diagnostics; <br/> using system. threading; </P> <p> namespace multithreading <br/>{< br/> class deadlock problem <br/>{< br/> Public static void main () <br/> {<br/> // due to competition, the lock is used. However, the lock problem is caused by deadlock, it is a thread waiting for another thread to unlock <br/> // while another thread is waiting for it to unlock the connection operation. The result is an infinite wait, silly B <br/> stateobject obj1 = new stateobject (); <br/> Stateobject obj2 = new stateobject (); <br/> New thread (New statethreadexec (obj1, obj2 ). method1 ). start (); <br/> // first let the first thread play and then start the second thread to compete with him, and finally the deadlock <br/> // The process is like this, thread 1 First locks S1 and then locks S2. If two threads are opened at the same time, the second thread can be grabbed after the first thread locks S1, at this time, the first <br/> thread has not locked S2, and the second thread is locked. At this time, the second thread will lock S1, but it cannot be locked, is occupied by the first entry. <Br/> // when he switches back to the first thread, he will continue to lock S2, and he will not be able to lock the second thread, and so on. <br/> thread. sleep (1000); <br/> New thread (New statethreadexec (obj1, obj2 ). method2 ). start (); <br/>}</P> <p> class stateobject <br/>{< br/> private int state = 5; </P> <p> Public void changestate (INT loop) <br/> {<br/> If (State = 5) <br/> {<br/> state ++; <br/> // if the value is not 6, execute the asserted display. <br/> trace. assert (State = 6, "the result is not 6 and appears in" + loop + "thread name:" + thread. currentthread. name); <br/>}</P> <p> state = 5; <br/>}</P> <p> class statethreadexec <br/>{< br/> stateobject S1; <br/> stateobject S2; </P> <p> Public statethreadexec (stateobject S1, stateobject S2) <br/>{< br/> This. s1 = S1; <br/> This. s2 = S2; <br/>}</P> <p> Public void Method1 () <br/>{< br/> for (INT I = 0; I <Int. maxvalue; I ++) <br/>{< br/> lock (S1) <br/>{< br/> lock (S2) <br/> {<br/> console. writeline ("method 1 is executing section" + I. tostring () + "times"); <br/> s1.changestate (0); <br/> s2.changestate (0 ); <br/>}</P> <p> Public void method2 () <br/> {<br/> for (INT I = 0; I <Int. maxvalue; I ++) <br/>{< br/> lock (S2) <br/>{< br/> lock (S1) <br/> {<br/> console. writeline ("method 2 is executing section" + I. tostring () + "times"); <br/> s1.changestate (0); <br/> s2.changestate (0 ); <br/>}< br/>