package demo1;/** * synchronized鎖重入 * Created by liudan on 2017/6/5. */public class MyThread5_synchronized1 { /** * 父子類同步必須 都 使用synchronized關鍵字 */ static class Main { public int count = 10; public synchronized void operationSub() { try { count--; System.err.println("Main print count = " + count); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Sub extends Main { public synchronized void operationSub() { while (count > 0) { try { count--; System.err.println("Sub print count = " + count); Thread.sleep(100); super.operationSub(); } catch (InterruptedException e) { e.printStackTrace(); } } } } /** * 關鍵字 synchronized 擁有鎖重入的功能, 也就是使用 synchronized 的時候,當一個線程獲得一個對象的鎖後,再次請求此對象 * 是是能夠再次獲得該對象的鎖。 */ public static void main(String[] args) { Thread t = new Thread(new Runnable() { @Override public void run() { Sub s = new Sub(); s.operationSub(); } }); t.start(); }}