java及jvm

类加载过程

2020-02-17  本文已影响0人  Gason_d796

类的加载过程

加载

加载.class文件的方式

链接

验证
准备
解析

初始化

public class ClassInitTest {
    private static int num = 1;

    static {
        num = 2;
        number = 20;
        System.out.println(number);// 会报错:非法的前向引用
    }

    private static int number = 10; // 链接的准备阶段:number=0 -->初始化<clinit>()按顺序依次:20 -->10

    public static void main(String[] args) {
        System.out.println(ClassInitTest.num);// 2
        System.out.println(ClassInitTest.number); // 0
    }
}
public class ClassInitTest {
    static class Father {
        public static int A = 1;

        static {
            A = 2;
        }
    }

    static class Son extends Father {
        public static int B = A
    }

    public static void main(String[] args) {
        System.out.println(Son.B);// 2
    }
}
public class ClassInitTest {
    public static void main(String[] args) {
        Runnable r = () -> {
            System.out.println(Thread.currentThread().getName() + "开始");
            DeadThread deadThread = new DeadThread();
            System.out.println(Thread.currentThread().getName() + "结束");
        };
        Thread t1 = new Thread(r, "线程1");
        Thread t2 = new Thread(r, "线程2");
        t1.start();
        t2.start();
    }

    class DeadThread {
        static {
            if (true) {
                System.out.println(Thread.currentThread().getName() + "初始化DeadThread");
                while (true) {

                }
            }

        }
    }
}

结果是只能输出一次 ‘初始化DeadThread’,如果初始化阻塞,会影响其他类无法使用该类

上一篇下一篇

猜你喜欢

热点阅读