常规代码块
1.代码块:是指单独使用“{ }”包括的一块区域。根据出现位置的不同,代码块分为四种:
2> 构造代码块。直接定义在类中的代码块称为构造代码块(构造块);
3> 静态代码块。直接使用static修饰的代码块称为静态代码块;
4> 同步代码块。格式:synchronized(同步监视器){同步代码块;}
TIP:
线程在执行同步代码块之前,需要预先获得对同步监视器的锁定,同步监视器通常是会被并发访问的同一共享资源。
同步代码块存在的意义在于:阻止多个线程对同一共享资源(临界区)的并发访问,且在任何时刻只能有一个线程可以获得对同步监视器的锁定,在完成执行同步代码块之后,该线程将释放对同步监视器的锁定。
2.代码块的执行顺序:
TIP:
3.静态代码块每次加载只执行一次!先于main方法的执行,在类加载时一同加载。
4.构造代码块,每一次实例化都将调用一次!
5.父类的优先级高于子类同级代码块。
代码块实例
public class CodesBlock {
{
System.out.println("Word天!");
}
static{
System.out.println("static blocks !");
}
public CodesBlock(){
System.out.println("Oh my god !");
}
static{
System.out.println("STATIC BLOCKS !!!");
}
public static void main(String[] args){
NormalBlocks();
ConstructorBlocks();
new CodesBlock();
new CodesBlock();
StaticBlocks();
}
private static void StaticBlocks() {
//静态代码块貌似只能在类中定义,无法在发法体中定义
// static{
//
// System.out.println("STATIC BLOCKS !");
// }
}
private static void ConstructorBlocks() {
//移至上方
}
private static void NormalBlocks() {
//普通代码块在使用的时候也限定了其成员的生命周期;
{
int x = 30;
System.out.println(x);
}
String x = "I've ever loved you ,honey";
System.out.println(x);
}
}
继承关系中的代码块及执行顺序
//父类:Inheritation
public class Inheritation {
static{
System.out.println("A 父类中的静态代码块");
}
{
System.out.println("B 父类中的构造代码块");
}
static{
System.out.println("C 父类中的静态代码块");
}
{
System.out.println("D 父类中的构造代码块");
}
}
//子类:SeqInInherited
public class SeqInInherited extends Inheritation {
{
System.out.println("a 子类中的构造代码块");
}
static{
System.out.println("b 子类中的静态代码块");
}
{
System.out.println("c 子类中的构造代码块");
}
static{
System.out.println("d 子类中的静态代码块");
}
/**
* 代码块在继承关系中的执行顺序
*
* A 父类中的静态代码块
C 父类中的静态代码块
b 子类中的静态代码块
d 子类中的静态代码块
X 主方法开始执行!
B 父类中的构造代码块
D 父类中的构造代码块
a 子类中的构造代码块
c 子类中的构造代码块
B 父类中的构造代码块
D 父类中的构造代码块
a 子类中的构造代码块
c 子类中的构造代码块
B 父类中的构造代码块
D 父类中的构造代码块
a 子类中的构造代码块
c 子类中的构造代码块
X 主方法执行结束!
*/
public static void main(String[] args){
System.out.println("X 主方法开始执行!");
SeqInInherited sia = new SeqInInherited();
SeqInInherited sib = new SeqInInherited();
SeqInInherited sic = new SeqInInherited();
System.out.println("X 主方法执行结束!");
}
}