Public class deadlock implements runnable {private Boolean flag; Private Static final object O1 = new object (); Private Static final object O2 = new object (); @ overridepublic void run () {string threadname = thread. currentthread (). getname (); system. out. println (threadname + ": Flag =" + flag); If (flag = true) {synchronized (O1) {try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (threadname + "Enter synchronization for O1 prepare to enter daily O2");/* will cause deadlock synchronized (O2) {system. out. println (threadname + "synchronization block O2");} * // solve the deadlock // synchronized (O2) {system. out. println (threadname + "synchronization block O2"); // }}} if (flag = false) {synchronized (O2) {try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. println (threadname + "Synchronize to O2 to prepare to enter O1"); synchronized (O1) {system. out. println (threadname + "synchronization block O1") ;}}} public static void main (string [] ARGs) {deadlock d1 = new deadlock (); deadlock D2 = new deadlock (); d1.flag = true; d2.flag = false; new thread (D1 ). start (); New thread (D2 ). start ();}}
When an object has not been released in the thread synchronization lock and another synchronization lock cannot obtain resources (the resource order used is the opposite), a deadlock may occur.
Solution 1: for exampleCodeTo cancel a synchronization lock
Solution 2: do not cancel, but use the same resource sequence.