public class HelloLoader {
public static void main(String[] args) {
System.out.println("谢谢ClassLoader加载我....");
System.out.println("你的大恩大德,我下辈子再报!");
}
}
它的加载过程是怎么样的呢?
类的加载过程:
1.加载
2.加载.class文件的方式
链接分为三个子阶段:验证 --> 准备 --> 解析
1.验证(Verify)
举例: 变量a在准备阶段会赋初始值,但不是1,而是0,在初始化阶段会被赋值为 1
public class HelloApp {
private static int a = 1; //prepare:a = 0 ---> initial : a = 1
public static void main(String[] args) {
System.out.println(a);
}
}
当我们代码中包含static变量的时候,就会有clinit方法 如果当前类不存在static变量,那么它的字节码文件是不会存在<clinit>( ) <clinit>()方法中的指令按语句在源文件中出现的顺序执行 构造器是虚拟机视角下的<init>()
public class ClinitTest {
//任何一个类声明以后,内部至少存在一个类的构造器
private int a = 1;
private static int c = 3;
public static void main(String[] args) {
int b = 2;
}
public ClinitTest(){
a = 10;
int d = 20;
}
}
public class ClinitTest1 {
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) {
//加载Father类,其次加载Son类。
System.out.println(Son.B); //2
}
}
public class DeadThreadTest {
public static void main(String[] args) {
Runnable r = () -> {
System.out.println(Thread.currentThread().getName() + "开始");
DeadThread dead = 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() + "初始化当前类");
while (true) {
}
}
}
}