2012-01-17 66 views
2

我是Java新手。任何人都可以解釋主要方法中發生了什麼?線程對象創建時設置線程的名字?

class Demo { 
    public static void main(String []args) { 
     //setting a name using the constructor 
     Thread t=new Thread("main"){ 
      //what is this? a static block?? need an explanation to this. 
      {setName("DemoThread");} 
     }; 
     //output is DemoThread. Since it set the name again. 
     System.out.println(t.getName()); 
    } 
} 

回答

7

這條線:

{setName("DemoThread");} 

稱爲初始化塊(或實例初始化塊)。它看起來像一個靜態初始化塊,但沒有關鍵字static。這對於匿名類非常有用,因爲它們不能命名構造函數。更多細節可以在here找到。

1

的代碼創建與

new Thread("main") { 

}; 

在該匿名類匿名Thread子類,有一個初始化塊:

{setName("DemoThread");} 
2
Thread t = new Thread("main") { 
    { 
     setName("DemoThread"); 
    } 
}; 

上面正在創建匿名內部類。 {}是Java中的一個實例初始化程序塊。這將是一個靜態塊,如果它有static { }

基本上,您可以從屬於實例(this)引用的實例初始化程序塊調用任何操作。

在這種情況下,它在Thread的當前實例上調用setName