Demonstration of deadlock in multiple threads
Package com. huowolf;/* deadlock meaning: * multiple threads are blocked at the same time, and one or all of them are waiting for the release of a resource. * The program cannot run properly because the thread is blocked indefinitely. ** Deadlock: Nested synchronization in synchronization. * But it may also be harmonious ** A common rule of thumb to avoid deadlocks is: * when several threads need to access Shared resources A, B, and C, ensure that each thread accesses them in the same order. * for example, access A first and access B and C. * // Deadlock example: class Test implements Runnable {private boolean flag; public Test (boolean flag) {this. flag = flag;} @ Overridepublic void run () {if (flag) {while (true) {synchronized (MyLock. locka) {System. out. println ("if locka"); synchronized (MyLock. lockb) {System. out. println ("if lockb") ;}}} else {while (true) {synchronized (MyLock. lockb) {System. out. println ("else lockb"); synchronized (MyLock. locka) {System. out. println ("else locka") ;}}}} class MyLock {static Object locka = new Object (); static Object lockb = new Object ();} public class DeadLockTest {public static void main (String [] args) {Thread t1 = new Thread (new Test (true )); thread t2 = new Thread (new Test (false); t1.start (); t2.start ();}}