一键搞定内网穿透 联行号查询|开户行查询 在线工具箱 藏经阁
当前位置:首页 / 杂记 / 正文
java代码块

普通代码块

就是平时写的方法或函数,如public int aaa(){},不再介绍。

静态代码块

JVM加载类时执行static代码块,只加载一次,static模块也只执行一次。
public class OrdersType {
 static {
  System.out.println("执行static");
 }
 public static final int A = 1;
 public static final int B = 2;
 //当执行主函数时,实际执行OrdersType.main()静态方法,这时要加载OrdersType类,发现有static块,便执行了static块。
 public static void main(String[] args) {
  System.out.println(A);
  System.out.println(B);
  //输出
  执行static
  1
  2
 }
int a = OrdersType.A; //JVM加载OrdersType类,发现有static块,便执行了static块。
int b = OrdersType.B; //OrdersType类已经加载过了,不再重新加载了,static也不再执行了。

构造代码块

构造代码块用一对“{}”表示,代码块位置没有具体的要求,但必须与类的成员同等级别,在括号的区域内,可以对所有该类的对象进行初始化,也就是说该类对象创建时都会执行到该代码块,并且其优先于构造函数执行。 也有地方说是java编译器在编译时会先将构造代码块中的代码移到构造函数中执行,构造函数中原有的代码最后执行。
public class A {
 {
  System.out.println("执行构造代码块"); //构造代码块{}前面不要任何修饰符
 }

 public A() {
  System.out.println("执行无参构造函数");
 }

 public A(int i) {
  System.out.println("执行有参构造函数");
 }

 public static void main(String[] args) {
  new A();
  new A(1);
  //输出
  执行构造代码块
  执行无参构造函数
  执行构造代码块
  执行有参构造函数
 }
}

同步代码块

使用synchronize关键字修饰,并使用"{}"括起来的代码片段.它表示在同一时间只能有一个线程进入到该方法快中,是一种多线程保护机制。
package ths;
public class Thread1 implements Runnable { 
  public void run() { 
   synchronized(this) { 
    for (int i = 0; i < 5; i++) { 
     System.out.println(Thread.currentThread().getName() + " synchronized loop " + i); 
    } 
   } 
  } 
  public static void main(String[] args) { 
   Thread1 t1 = new Thread1(); 
   Thread ta = new Thread(t1, "A"); 
   Thread tb = new Thread(t1, "B"); 
   ta.start(); 
   tb.start(); 
  } 
}
输出
  A synchronized loop 0 
  A synchronized loop 1 
  A synchronized loop 2 
  A synchronized loop 3 
  A synchronized loop 4 
  B synchronized loop 0 
  B synchronized loop 1 
  B synchronized loop 2 
  B synchronized loop 3 
  B synchronized loop 4