2013-09-28 80 views
-5

我們可以創建接口但不是對象的引用。但爲什麼線程構造函數接受新的Runnable()看起來像對象。 例如線程t =新線程(new Runnable(){});關於接口和線程的困惑

回答

0

Thread構造就像

Thread t = new Thread(Runnable runn) 

,而不是(新的Runnable(){})。 當我們做一些事情如下圖所示

Thread t = new Thread(new Runnable() { 
    @Override 
    public void run() { 
     // TODO Auto-generated method stub 

    } 
}); 

它基本上是要求我們在Runnable的inteface定義爲實現run方法。

或者我們可以創建一個新類,它實現Runnable接口並在那裏實現run方法。

public class ThreadA implements Runnable { 
    public void run() { 
     // thread code goes here    
    } 
} 

,然後我們可以使用初始化

Thread t = new Thread(new ThreadA()); 

希望這回答了你的疑惑一個新的線程。隨時詢問是否存在疑問。

+0

非常感謝....我認爲這對我來說已經足夠了 – user2826111