標籤:src 分享 runnable private user exception 內部使用 img ati
1.
1 /** 2 * lock.getHoldCount()方法:只能在當前調用線程內部使用,不能再其他線程中使用 3 * 那麼我可以在m1方法裡去調用m2方法,同時m1方法和m2方法都持有lock鎖定即可 測試結果holdCount數遞增 4 * 5 */ 6 public class TestHoldCount { 7 8 //重入鎖 9 private ReentrantLock lock = new ReentrantLock();10 11 public void m1(){12 try {13 lock.lock();14 System.out.println("進入m1方法,holdCount數為:" + lock.getHoldCount());15 16 //調用m2方法17 m2();18 19 } catch (Exception e) {20 e.printStackTrace();21 } finally {22 lock.unlock();23 }24 }25 26 public void m2(){27 try {28 lock.lock();29 System.out.println("進入m2方法,holdCount數為:" + lock.getHoldCount());30 } catch (Exception e) {31 e.printStackTrace();32 } finally {33 lock.unlock();34 }35 }36 37 38 public static void main(String[] args) {39 TestHoldCount thc = new TestHoldCount();40 thc.m1();41 /*42 進入m1方法,holdCount數為:143 進入m2方法,holdCount數為:2 */44 }45 }View Code
2.
1 public class UseReentrantLock { 2 3 private Lock lock = new ReentrantLock(); 4 5 public void method1(){ 6 try { 7 lock.lock(); 8 System.out.println("當前線程:" + Thread.currentThread().getName() + "進入method1.."); 9 Thread.sleep(1000);10 System.out.println("當前線程:" + Thread.currentThread().getName() + "退出method1..");11 Thread.sleep(1000);12 } catch (InterruptedException e) {13 e.printStackTrace();14 } finally {15 16 lock.unlock();17 }18 }19 20 public void method2(){21 try {22 lock.lock();23 System.out.println("當前線程:" + Thread.currentThread().getName() + "進入method2..");24 Thread.sleep(2000);25 System.out.println("當前線程:" + Thread.currentThread().getName() + "退出method2..");26 Thread.sleep(1000);27 } catch (InterruptedException e) {28 e.printStackTrace();29 } finally {30 31 lock.unlock();32 }33 }34 35 public static void main(String[] args) {36 37 final UseReentrantLock ur = new UseReentrantLock();38 Thread t1 = new Thread(new Runnable() {39 @Override40 public void run() {41 ur.method1(); //同一把鎖 ur42 ur.method2(); //同一把鎖 ur43 }44 }, "t1");45 46 t1.start();47 try {48 Thread.sleep(10);49 } catch (InterruptedException e) {50 e.printStackTrace();51 }52 //System.out.println(ur.lock.getQueueLength());53 }54 /*55 當前線程:t1進入method1..56 當前線程:t1退出method1..57 當前線程:t1進入method2..58 當前線程:t1退出method2.. */59 60 }View Code
多線程27 -- ReentrantLock