Detailed Explanation of Four Code Blocks in Java Programming

  • 2021-09-24 22:20:56
  • OfStack

In Java programming, code blocks refer to code enclosed by "{}". Let's look at these four code blocks.

1. Common code blocks

Refers to the method body of the method in the class.


public void xxx(){ 
      //code 
  } 

2. Building blocks

In the following code snippet enclosed with "{}", the building block is called when the object is created, every time the object is created, and takes precedence over the class constructor (both parameterized and nonparameterized). The variables defined in the building block are local variables.


public class Client {
    {// Construct code block 
        System.out.println(" Execute the construction code block ");
    }

    publicClient() {
        System.out.println(" Execute a parameterless constructor ");
    }

    publicClient(String string) {
        System.out.println(" Execute a parameterized constructor ");
    }
}

3. Static block

The following code snippet enclosed in static "{}" executes only once the first time this class is loaded, and static blocks take precedence over building blocks.


public class Demo
{
    public Demo()
    {
        System.out.print(" Default constructor! -->");
    }

// Construct code block 

{
    System.out.print(" Construct code block! -->");
}

// Static code block 
static
{
    System.out.print(" Static code block! -->");
}

public static void test()
{
    {
        System.out.println(" Code blocks in common methods! ");
    }
}
}
public static void main(String[]args)
{
    Demo d = new Demo();
    d.test();
}
/*
 The running output is: 
 Static code block! --> Construct code block! --> Default constructor! --> Code blocks in common methods! 
*/

4. Synchronize code blocks

The following code blocks are enclosed by synchronized (obj) {}. In a multithreaded environment, reading and writing shared data needs mutual exclusion, otherwise it will lead to different data. synchronized is commonly used to modify the method, and its semantics is that any thread entering synchronized needs to obtain the object lock first. If it is occupied, it will block, thus realizing mutual exclusive access to shared resources. And synchronized also has a price. A common scenario is that in a lengthy method, only one short piece of code needs to access shared resources. In this case, using synchronization block, only this short piece of code is written in synchronized block, which can not only realize synchronous access, but also reduce the overhead introduced by synchronization. Synchronization code blocks must be written in methods.


class Ticket implements Runnable //extends Thread
{
    object obj=new object();// Shared object, used to record whether other processes are accessing it 
    private static int tick=100;
    public void run()              /* You can't write the synchronization function here, otherwise other threads can't use it and need to write it separately 1 Synchronization function */
    {
        while(true)
        {   synchronized(obj)
            {
                if(tick>0)
                { 
                    try
                    {
                        Thread.sleep(10);   /* Sleep every time you run 1 Under */
                    }
                    catch(Exception e)
                    {
                        
                    }
                    System.out.println(Thread.currentThread().getName()+"sale:--"+tick--);
                }
            }
          }
    }
}

Related articles: