zoukankan      html  css  js  c++  java
  • Java 学习笔记之 父子类Synchronized

    父子类Synchronized:

    我们通过一个例子来验证下,父类和子类的Synchronized方法被同时调用,是否是同步的。

    public class FatherClass {
    
        synchronized public void callFather(){
            try {
                System.out.println("------------Call Father start------");
                Thread.sleep(10000);
                System.out.println("------------Call Father end------");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    public class SunClass extends FatherClass {
    
        synchronized public void callSon(){
            try {
                System.out.println("------------Call Son start------");
                Thread.sleep(10000);
                System.out.println("------------Call Son end------");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    
    }
    
    public class FatherThread extends Thread {
        private FatherClass f;
        public FatherThread(FatherClass f) {
            this.f = f;
        }
        @Override
        public void run() {
            super.run();
            f.callFather();
        }
    }
    
    public class SunThread extends Thread {
        private SunClass s;
    
        public SunThread(SunClass s) {
            this.s = s;
        }
    
        @Override
        public void run() {
            super.run();
            s.callSon();
        }
    }
    
    public class ThreadRunMain {
        public static void main(String[] args) {
            testSyncFSThread();
        }
    
        public static void testSyncFSThread(){
            SunClass sc = new SunClass();
            SunThread st = new SunThread(sc);
            st.start();
            FatherThread ft = new FatherThread(sc);
            ft.start();
        }
    }

    运行结果:

    通过验证,回答是Yes。

  • 相关阅读:
    MyBatis学习之二----应用
    网逛收藏
    Dubbo+Zookeeper 入门Demo
    React + umi +antd+antv/g6 实现力图
    npm、yarn 简单使用记录
    React yarn安装umi后 umi -v查询版本失败
    Eclipse 快速打开文件所在的本地目录
    Windows激活工具
    Win7 node多版本管理gnvm采坑记录
    自定义环形进度条RoundProgressBar
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7726931.html
Copyright © 2011-2022 走看看