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

    运行结果:

  • 相关阅读:
    还记得吗
    PAT A 1065. A+B and C (64bit) (20)
    畅通project(杭电1863)
    cocos2d-x 3.0游戏实例学习笔记《卡牌塔防》第七步---英雄要升级&属性--解析csv配置文件
    热烈祝贺Polymer中文组织站点上线
    具体解释HTML中的window对象和document对象
    oc15--文档安装
    oc14--匿名对象
    oc13--pragma mark
    oc12--对象作为参数
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7721727.html
Copyright © 2020-2023  润新知