synchronized的其他用法 原

用法一、關於函數的調用

代碼:

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();
    }
}

運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章