美文网首页
(Synchronized)可重入性

(Synchronized)可重入性

作者: 讲道理很没道理 | 来源:发表于2019-02-26 14:13 被阅读0次

什么是可重入:指的是同一线程的外层函数获得锁之后,内层函数可以直接再次获得该锁。
(摇号-一次摇号只给一辆车上牌照 ,还需上就要重新摇号(不可重入))

好处:避免死锁,提升封装性。
粒度:线程而非调用
情况1:证明一个方法是可重入的


/**
 * @author sxylml
 * @Date : 2019/2/26 13:52
 * @Description:
 * 可重入粒度测试看,递归调用本方法
 */
public class SynchronizedRecursion {
    int a = 0;

    public static void main(String[] args) {

        SynchronizedRecursion synchronizedRecursion = new SynchronizedRecursion();
        synchronizedRecursion.method1();
    }

    private void method1() {
        System.out.println("这是method1() ,a=" + a);
        if (a == 0) {
            a++;
            method1();
        }
    }

}

情况2:证明可重入不要求是同一个方法


/**
 * @author sxylml
 * @Date : 2019/2/26 14:01
 * @Description:
 */
public class SynchronizedOtherMethod {

    public synchronized void method1(){

        System.out.println("method1");
        method2();
    }

    public synchronized void method2(){
        System.out.println("method2");
    }

    public static void main(String[] args) {
        SynchronizedOtherMethod synchronizedOtherMethod = new SynchronizedOtherMethod();
        synchronizedOtherMethod.method1();
    }
}

情况3:证明可重入不要求是同一个类种的


/**
 * @author sxylml
 * @Date : 2019/2/26 14:07
 * @Description:
 */
public class SynchronizedSuper {
    public synchronized void doSometing() {

        System.out.println("我是父类的方法");
    }


}

class SubClass extends SynchronizedSuper {

    @Override
    public synchronized void doSometing() {
        System.out.println("我是子类方法");
        super.doSometing();
    }

    public static void main(String[] args) {
        SubClass s = new SubClass();
        s.doSometing();
    }
}

粒度是线程,而不是调用,具备可重入性。

不可中断性

相关文章

网友评论

      本文标题:(Synchronized)可重入性

      本文链接:https://www.haomeiwen.com/subject/pssayqtx.html