zoukankan      html  css  js  c++  java
  • Java 学习笔记之 Synchronized锁重入

    Synchronized锁重入:

    当一个线程得到一个对象锁后,再次请求此对象锁时是可以再次得到该对象的锁。这也证明在一个Synchronized方法/块的内部调用本类的其他Synchronized方法/块时候,是永远可以得到锁的。

    public class SyncReUseService {
        synchronized public void service1(){
            System.out.println("service1");
            service2();
        }
    
        synchronized public void service2(){
            System.out.println("service2");
            service3();
        }
    
        synchronized public void service3(){
            System.out.println("service3");
        }
    }
    
    public class SyncReUseServiceThread extends Thread {
        @Override
        public void run() {
            super.run();
            SyncReUseService service = new SyncReUseService();
            service.service1();
        }
    }
    
    public class ThreadRunMain {
        public static void main(String[] args) {
            testSyncReUseServiceThread();
        }
    
        public static void testSyncReUseServiceThread(){
            SyncReUseServiceThread t = new SyncReUseServiceThread();
            t.start();
        }
    }

    运行结果:

    当存在父子继承关系时,子类也可以通过“可重入锁”调用父类的同步方法。

    public class FatherClass {
        public int i = 10;
        synchronized public void operateIMainMethod(){
            try {
                i--;
                System.out.println("Father class print i = " + i);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    public class SunClass extends FatherClass {
        synchronized public void operateISubMethod(){
            try {
                while (i > 0) {
                    i--;
                    System.out.println("Sun class print i = " + i);
                    Thread.sleep(100);
                    this.operateIMainMethod();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
    public class FatherSunThread extends Thread {
        @Override
        public void run() {
            super.run();
            SunClass sub = new SunClass();
            sub.operateISubMethod();
        }
    }
    
    public class ThreadRunMain {
        public static void main(String[] args) {
            testFatherSunThread();
        }
    
        public static void testFatherSunThread(){
            FatherSunThread t = new FatherSunThread();
            t.start();
        }
    }

    运行结果:

  • 相关阅读:
    《大道至简》读后感
    第一周学习总结-Java
    c++与java的几个不同点
    单调队列 滑动窗口模型
    计算空间
    关于dp初始化问题
    康托展开小结-
    Vm-Ubuntu下配置Qt开发环境
    C++学习013多态
    C++学习012友元
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7721727.html
Copyright © 2011-2022 走看看