代码块:
用{}
括起来的一段代码,代码块可以分为四种:普通代码块、构造块、静态代码块、同步代码块
定义在方法中的代码块。
将代码块直接定义在类中,则称为构造代码块。会优先于构造方法运行,每构造类一次就执行一次。
使用static修饰的构造块称为静态代码块.
使用 synchronized ()
修饰的普通代码块
测试题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| class HelloA { public HelloA() { System.out.println("helloA"); } { System.out.println("i am class A"); } static { System.out.println("staticA"); } } public class HelloB extends HelloA { public HelloB() { System.out.println("helloB"); } { System.out.println("i am class B"); } static { System.out.println("staticB"); }
public static void main(String[] args) throws InterruptedException { { System.out.println("000"); } new HelloB(); synchronized ("a") { System.out.println("111"); TimeUnit.SECONDS.sleep(2); } { System.out.println("222"); }
} }
|
运行结果:
1 2 3 4 5 6 7 8 9 10
| staticA staticB 000 i am class A helloA i am class B helloB 111 222
|