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。

  • 相关阅读:
    HMS11.Image, TabList与Tab, Picker
    HMS10. JavaUI框架, Text, Button,TextField
    HMS09.Ability
    HMS08. 快速入门
    HMS07.应用的运行、DeBug、HiLog、HiTrace
    批量插入100万条数据
    关于ios7 UINavigationController.interactivePopGestureRecognizer手势集成
    iOS 常用框架介绍
    iOS 内存管理(转载)
    cocoapod 最新安装使用步骤
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7726931.html
Copyright © 2011-2022 走看看