java static code
static{}代码块在一个进程中只会执行一次。
public class XX { public XX() { System.out.println("XX()"); } }
public class Test {
static {
System.out.println("static code thread ID:"
+ Thread.currentThread().getId());
}
private static final XX x = new XX();
public static void main(String[] args) {
System.out.println("main thread ID:" + Thread.currentThread().getId());
new Thread() {
@Override
public void run() {
new Test().print();
}
}.start();
new Thread() {
@Override
public void run() {
new Test().print();
}
}.start();
}
public void print() {
System.out.println("thread ID:" + Thread.currentThread().getId());
}
}
-----------------------------------
static code thread ID:1
XX()
main thread ID:1
thread ID:8
thread ID:9
---------------------------------------------------------------------------------------
有2种情况下静态代码会执行:
1. new 一个Extend类
2. 调用一个Extend类中实现的(而非继承下来的)静态方法
public class Base {
public static String who = "Mr. Base";
Base(){
}
static {
System. out.println("static block in Base" );
}
public static void functionInBase(){
System. out.println("static function in Base! -- " + who);
}
public void showWho(){
System. out.print(who);
}
}
public class Extend extends Base {
public static String who = "Mr. Extend";
static {
System.out.println("static block in Extend");
}
public static void functionInExtend() {
System.out.println("static function in Extend!");
}
Extend() {
}
}
public class TT {
public static void main(String[] args) {
Extend.functionInBase();
System.out.println();
Extend ex = new Extend();
System.out.println();
ex.showWho();
System.out.println(Extend.who);
}
}
static block in Base
static function in Base! -- Mr. Base
static block in Extend
Mr. BaseMr. Extend

浙公网安备 33010602011771号