1 Public classmain{2 3 /*Analog Deadlock4 * 5 * Persona to get B to give A to B6 * PERSONB's got A to give B to a .7 * 8 * 9 * Ten */ One A Public Static voidMain (string[] args) { - NewThread (NewRun (true) . Start (); - NewThread (NewRun (false) . Start (); the } - - } - + classpersona{ - + Public voidsay () { ASYSTEM.OUT.PRINTLN ("A said: Give me B"); at } - - Public voidGetb () { -System.out.println ("A Got the stuff of B"); - } - } in - classpersonb{ to Public voidsay () { +SYSTEM.OUT.PRINTLN ("B said: Give Me a"); - } the * Public voidGeta () { $System.out.println ("B Got something of a");Panax Notoginseng } - } the + classRunImplementsrunnable{ A the //must be a static object + StaticPersonA A =NewPersonA (); - StaticPersonb B =Newpersonb (); $ Private BooleanAGIVEB;//whether it's A to B $ - PublicRun (BooleanAGIVEB) { - This. AGIVEB =AGIVEB; the } - Wuyi @Override the Public voidrun () { - if(AGIVEB) { Wu synchronized(b) { - B.say (); About Try { $Thread.Sleep (500); -}Catch(interruptedexception e) { - e.printstacktrace (); - } A synchronized(a) { +System.out.println ("A gave a B"); the B.geta (); - } $ } the}Else{ the synchronized(a) { the A.say (); the Try { -Thread.Sleep (500); in}Catch(interruptedexception e) { the e.printstacktrace (); the } About synchronized(b) { theSystem.out.println ("B gave a" B.)); the A.getb (); the } + } - } the }Bayi the}
Java Impersonation thread deadlock