用法一、關於函數的調用
代碼:
public class Thread2 { public synchronized void method1(){ System.out.println("method1.."); method2(); } public synchronized void method2(){ System.out.println("method2.."); method3(); } public synchronized void method3(){ System.out.println("method3.."); } public static void main(String[] args) { final Thread2 t2 = new Thread2(); Thread thread = new Thread(() -> t2.method1()); thread.start(); } }
執行結果:
用法二、關於父類,子類的synchronized用法
代碼:
public class Thread3 { static class Main{ public int i =10; public synchronized void operationSup(){ try { i--; System.out.println("Main print i = "+i); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } static class Sub extends Main{ public synchronized void operationSub(){ try { while (i>0){ i--; System.out.println("Sub print i = "+i); Thread.sleep(100); this.operationSup(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { Thread t1 = new Thread(() -> { Sub sub = new Sub(); sub.operationSub(); }); t1.start(); } }
運行結果: