[The Java] code blocks

 

Code block is divided into four categories

  1. Common code block
  2. Building blocks
  3. Static code block
  4. Sync block (multithreaded)

1. Ordinary block

In the method of {} is the code segments common circumferential block

2. The building block


public class T2 {
	{
		System.out.println("First construction block");
	}	
	public T2 () {
		System.out.println("Official Construction function");
	}
	{
		System.out.println("Second construction block");
	}
	public final static void main(String[] args) {
		T2 t = new T2();
	}
	
}

operation result:

analysis:

Building blocks is not defined in the class plus static modified {} snippet

Class instantiation, call sequence building blocks before the constructor, and each instantiation will be invoked, so called building blocks, and the order-independent and code, can be seen from the above sample code

3. Static block


public class T2 {
	{
		System.out.println("First construction block");
	}	
	public T2 () {
		System.out.println("Official Construction function");
	}
	{
		System.out.println("Second construction block");
	}
	static {
		System.out.println("Static constuction block 1");
	}
	static  {
		 System.out.println("Static construction block 2");
	}
	public final static void main(String[] args) {
		T2 t = new T2();
		{
			System.out.println("This is an average block");
		}
	}
	
}

operation result:

analysis:

You can see the static code block is executed before the main function, and no matter how many times instantiated, static code block will be executed once

Summary of, static blocks using a static modification {} , is used to initialize static class code block, any method can not be placed in the body, like the static method, a static block of code can not access the non-static methods and variables, static code block is only will be executed once, the order of execution is determined in the order defined (static code when a plurality of blocks), define the first implementation.

4. The sync block

After supplement

Guess you like

Origin blog.csdn.net/chenhanxuan1999/article/details/91480463