synchronized关键字的可重入性

泄露秘密 提交于 2019-12-01 22:01:48
/**父类*/public class SynchronizedDemo1 implements Runnable {    @Override    public void run() {        try {            method();        } catch (InterruptedException e) {            e.printStackTrace();        }    }    public  void method() throws InterruptedException {        synchronized(SynchronizedDemo1.class) {            System.out.println(Thread.currentThread().getName() + " super start");            Thread.sleep(3000);            System.out.println(Thread.currentThread().getName() + " super finished");        }    }}//子类,在子类的main方法中调用子类的synchronized方法,在method方法中调用父类的method方法,是可以执行父类的method方法的,也就是说对于一个锁对象而言,这是传递过去的,也即在这个线程中这个锁是可以重复利用的,那么如果锁都不是同一个对象的话,自然也就不存在什么同步了(一开始没反应过来)class Son extends SynchronizedDemo1{    public void method() throws InterruptedException {        synchronized(Son.class) {            System.out.println(Thread.currentThread().getName() + " son start");            Thread.sleep(3000);            super.method();            System.out.println(Thread.currentThread().getName() + " son finished");        }    }    public static void main(String[] args) {        Son s=new Son();        try {            s.method();        } catch (InterruptedException e) {            e.printStackTrace();        }    }}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!