1.
1 /**2 * Lock.getholdcount () method: can only be used within the current calling thread and cannot be used in other threads3 * Then I can call the M2 method in the M1 method, while the M1 method and M2 method both hold lock locks to increase the number of test results Holdcount4 *5 */6 Public classTestholdcount {7 8 //re-entry lock9 PrivateReentrantlock lock =NewReentrantlock ();Ten One Public voidM1 () { A Try { - Lock.lock (); -System.out.println ("Enter M1 method, Holdcount number is:" +Lock.getholdcount ()); the - //calling the M2 method - m2 (); - +}Catch(Exception e) { - e.printstacktrace (); +}finally { A Lock.unlock (); at } - } - - Public voidm2 () { - Try { - Lock.lock (); inSystem.out.println ("Enter M2 method, holdcount number is:" +Lock.getholdcount ()); -}Catch(Exception e) { to e.printstacktrace (); +}finally { - Lock.unlock (); the } * } $ Panax Notoginseng - Public Static voidMain (string[] args) { theTestholdcount THC =NewTestholdcount (); + thc.m1 (); A /* the Enter the M1 method, the number of Holdcount is: 1 + Enter the M2 method, the number of Holdcount is: 2*/ - } $}
View Code
2.
1 Public classUsereentrantlock {2 3 PrivateLock lock =NewReentrantlock ();4 5 Public voidmethod1 () {6 Try {7 Lock.lock ();8System.out.println ("Current thread:" + thread.currentthread (). GetName () + "Enter method1 ...");9Thread.Sleep (1000);TenSystem.out.println ("Current thread:" + thread.currentthread (). GetName () + "Exit method1 ..."); OneThread.Sleep (1000); A}Catch(interruptedexception e) { - e.printstacktrace (); -}finally { the - Lock.unlock (); - } - } + - Public voidmethod2 () { + Try { A Lock.lock (); atSystem.out.println ("Current thread:" + thread.currentthread (). GetName () + "Enter method2 ..."); -Thread.Sleep (2000); -System.out.println ("Current thread:" + thread.currentthread (). GetName () + "Exit Method2 ..."); -Thread.Sleep (1000); -}Catch(interruptedexception e) { - e.printstacktrace (); in}finally { - to Lock.unlock (); + } - } the * Public Static voidMain (string[] args) { $ Panax Notoginseng FinalUsereentrantlock ur =NewUsereentrantlock (); -Thread T1 =NewThread (NewRunnable () { the @Override + Public voidrun () { AUr.method1 ();//the same lock ur theUR.METHOD2 ();//the same lock ur + } -}, "T1"); $ $ T1.start (); - Try { -Thread.Sleep (10); the}Catch(interruptedexception e) { - e.printstacktrace ();Wuyi } the //System.out.println (Ur.lock.getQueueLength ()); - } Wu /* - Current thread: T1 into method1. About Current thread: T1 exit method1. $ Current thread: T1 into method2. - Current thread: T1 exit method2.*/ - -}
View Code
Multithreading--Reentrantlock