在使用synchronized時,當一個線程獲得一個對象鎖後,再次請求此對象鎖時是能夠再次獲得該對象鎖的.這也證實在一個synchronized方法/塊的內部調用本類的其餘synchronized方法/塊時,是永遠能夠獲得鎖的.ide
public class ThreadReenter { synchronized public void firstService() { System.out.println("This is the first service!"); secondService(); } synchronized public void secondService() { System.out.println("This is the second service!"); thirdService(); } synchronized public void thirdService() { System.out.println("This is the third service!"); } }
public class FirstThread extends Thread { @Override public void run(){ ThreadReenter threadReenter = new ThreadReenter(); threadReenter.firstService(); } }
public class Run { public static void main(String[] args) { FirstThread firstThread = new FirstThread(); firstThread.start(); } }
運行結果:this
可重入鎖的概念:線程
本身能夠再次獲取本身的內部鎖.好比一個線程獲取了某個對象的鎖,此時這個對象的鎖尚未釋放,當這個線程想要獲取這個對象的鎖的時候仍是能夠獲取的,若是不能夠鎖重入的話,就會形成死鎖.對象
注:可重入鎖也適用於父子類繼承的環境中.繼承
public class ThreadReenter { public int i = 10; synchronized public void ancestor(){ try{ i--; System.out.println("the ancestor i = " + i); Thread.sleep(200); }catch (Exception e){ e.printStackTrace(); } } }
public class SonOfThreadReenter extends ThreadReenter{ synchronized public void Posterity(){ try{ while(i > 0){ i--; System.out.println("the Posterity i = " + i); Thread.sleep(200); this.ancestor(); } }catch (Exception e){ e.printStackTrace(); } } }
public class FirstThread extends Thread { @Override public void run(){ SonOfThreadReenter sonOfThreadReenter = new SonOfThreadReenter(); sonOfThreadReenter.Posterity(); } }
public class Run { public static void main(String[] args) { FirstThread firstThread = new FirstThread(); firstThread.start(); } }
運行結果:同步
當存在父子類繼承時,子類是徹底能夠經過可重入鎖調用父類的同步方法的.it