When a thread executes a code exception, the locks it holds are automatically freed
Public classMyObject {Private inti = 1; synchronized Public voidMethodA ()throwsinterruptedexception {System.out.println ("Begin MethodA Threadname=" +Thread.CurrentThread (). GetName ()); if(i==1){ Throw Newinterruptedexception (); } System.out.println ("End MethodA"); } synchronized Public voidMethodB ()throwsinterruptedexception {System.out.println ("Begin MethodB Threadname=" +Thread.CurrentThread (). GetName ()); System.out.println ("End MethodB"); }}
Threada and THREADB
Public classThreadaextendsThread {PrivateMyObject MyObject; PublicThreada (MyObject MyObject) { This. MyObject =MyObject; } Public voidrun () {Try{Myobject.methoda (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }} Public classThreadbextendsThread {PrivateMyObject MyObject; Publicthreadb (MyObject MyObject) { This. MyObject =MyObject; } Public voidrun () {Try{myobject.methodb (); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } }}
View Code
Run
Public class Run { publicstaticvoid main (string[] args) { new MyObject (); New Threada (object); Threada.setname ("A"); Threada.start (); New threadb (object); Threadb.setname ("B"); Threadb.start (); }}
View Code
Java Multithreading (ii) Synchronized throw exception lock auto dismiss