Java代碼塊

來源:互聯網
上載者:User

標籤:java   執行   sync   new   使用   記憶體   []   test   同步代碼塊   

普通代碼塊:

      方法中出現,限定變數生命週期,及早釋放,提高記憶體利用率。

構造代碼塊:

      在類中方法外出現,構造塊會在建立對象時被調用,每次調用構造都執行,並且在構造方法前執行。

靜態代碼塊:

     方法外出現,並加上 static 修飾;用於給類進行初始化,在載入的時候就執行,並且只執行一次。

同步代碼塊:

        使用synchronized(){}包裹起來的代碼塊,在多線程環境下,對共用資料的讀寫操作是需要互斥進行的,否則會導致資料的不一致性。同步代碼塊需要寫在方法中。

例子1:

 

class Student {   static {       System.out.println("Student 靜態代碼塊");   }   {       System.out.println("Student 構造代碼塊");   }   public Student() {       System.out.println("Student 構造方法");   }}

 

 

 

class Demo2_Student {    static {        System.out.println("Demo2_Student 靜態代碼塊");    }    public static void main(String[] args) {        System.out.println("我是 main 方法");        Student s1 = new Student();        Student s2 = new Student();    }}            

 

執行流程:首先需要載入類 Demo2_Student,在載入之後就執行靜態代碼塊。然後執行主方法。建立 student 對象需要先載入類,載入類時又執行了靜態代碼塊。然後在 new 對象之前,要執行構造代碼塊,然後才執行狗仔方法。

例子2:

 

class Test2_Extends {    public static void main(String[] args) {        Zi z = new Zi();    }}

 

class Fu {    static {        System.out.println("靜態代碼塊 Fu");    }    {        System.out.println("構造代碼塊 Fu");    }    public Fu() {        System.out.println("構造方法 Fu");    }}                
class Zi extends Fu {    static {        System.out.println("靜態代碼塊 Zi");    }    {    System.out.println("構造代碼塊 Zi");    }    public Zi() {        System.out.println("構造方法 Zi");    }}        

 

 

 

執行流程:

1,jvm 調用了 main 方法,main 進棧
2,遇到 Zi z = new Zi();會先將 Fu.class 和 Zi.class 分別載入進記憶體,再建立對象,當 Fu.class載入進記憶體父類的靜態代碼塊會隨著 Fu.class 一起載入,當 Zi.class 載入進記憶體,子類的靜態代碼塊會隨著 Zi.class 一起載入。第一個輸出靜態代碼塊 Fu,第二個輸出靜態代碼塊 Zi
3,然後走 Zi 類的構造方法,因為 java 中是分層初始化的,先初始化父類,再初始化子類,所以又先走的父類構造,但是在執行父類構造時,發現父類有構造代碼塊,構造代碼塊是優先於構造方法執行的所以第三個輸出構造代碼塊 Fu,第四個輸出構造方法 Fu
4,Fu 類初始化結束,子類初始化,第五個輸出的是構造代碼塊 Zi,構造方法 Zi

 

 

Java代碼塊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.