虚拟机类加载--2.类的初始化
初始化是类加载过程的最后一步,但由于比较重要,故放在前面先讲。
在前面的连接(准确来说是准备)阶段,类的变量已经被赋予默认值(如int类型为0,布尔类型为false,引用类型为null等)。而在初始化阶段,则根据程序员通过程序制定的主观计划去初始化类变量和其他资源。或者可以从另一个角度来表达:初始化阶段是执行类构造器
1.
2.
3.由于父类的
1 package com.khlin.initialization; 2 3 public class App { 4 5 public static void main(String[] args) { 6 System.out.println(Sub.b); 7 } 8 9 static class Parent { 10 public static int a = 1; 11 static { 12 a = 2; 13 } 14 } 15 16 static class Sub extends Parent { 17 public static int b = a; 18 } 19 }
4.
5.接口中不能使用静态语句块,但仍然有变量初始化的赋值操作,所以接口和类一样都会生成
6.虚拟机会保证一个类的
1 package com.khlin.initialization; 2 3 public class EndlessLoop { 4 5 static { 6 if (true) { 7 System.out.println(Thread.currentThread() + " init EndlessLoop"); 8 while (true) { 9 } 10 } 11 } 12 13 }
1 public static void main(String[] args) { 2 Runnable runnable = new Runnable() { 3 4 @Override 5 public void run() { 6 System.out.println(Thread.currentThread() + " is running...."); 7 EndlessLoop endlessLoop = new EndlessLoop(); 8 System.out.println(Thread.currentThread() + " runs over"); 9 } 10 }; 11 12 Thread threadA = new Thread(runnable); 13 Thread threadB = new Thread(runnable); 14 threadA.start(); 15 threadB.start(); 16 }
结果会显示: