2010-11-12 64 views
3

當我們子類Thread時,我們重寫它的run方法嗎?我們知道Thread類本身實現了Runnable,但Runnable類中沒有定義run方法的主體。當子類從線程父類擴展時我們是否覆蓋run方法

這是畫面在我的腦海:

Runnable接口 - 父類,它有它的運行方法,空體。

Thread-兒童,

CLASSA擴展兒童Thread-兒童,

當我們定義運行 「ClassA的」()方法時,我們它將覆蓋運行的類聲明的運行方法? 謝謝你的時間。

回答

8

有兩種方法可以定義線程的行爲:子類Thread類,或實現Runnable接口。

對於第一種方式,簡單地擴展Thread類,並用自己的實現覆蓋run()方法:

public class HelloThread extends Thread { 
    @Override 
    public void run() { 
     System.out.println("Hello from a thread!"); 
    } 
} 

public class Main { 
    // main method just starts the thread 
    public static void main(String args[]) { 
     (new HelloThread()).start(); 
    } 
} 

然而,實施該邏輯針對線程的優選方法是通過創建一個類實現Runnable接口:

public class HelloRunnable implements Runnable { 
    @Override 
    public void run() { 
     System.out.println("Hello from a thread!"); 
    } 
} 

public class Main { 
    // notice that we create a new Thread and pass it our custom Runnable 
    public static void main(String args[]) { 
     (new Thread(new HelloRunnable())).start(); 
    } 
} 

即實現Runnable是優選的,原因是它提供的線程的行爲和線程本身之間的明確分離。例如,使用線程池的時候,你從來沒有真正從頭開始創建線程,你只是傳遞一個Runnable的框架,它會執行它的可用線程您:

public class Main { 
    public static void main(String args[]) { 
     int poolSize = 5; 
     ExecutorService pool = Executors.newFixedThreadPool(poolSize); 
     pool.execute(new HelloRunnable()); 
    } 
} 

延伸閱讀:

+0

很好的解釋。 :) – casablanca 2010-11-12 03:55:56

+0

這真的是很好的信息,但我沒有得到我的答案,我們是否覆蓋Thread類中定義的run方法。 – ranjanarr 2010-11-12 04:05:03

+0

@ranjanarr再次閱讀答案。第二句話尤其如此。 – 2010-11-12 04:06:48

0

只有在您要重寫線程的功能或提高其性能時,才應該擴展線程。

界面告訴你,如果你使用這個界面,你會得到funcationality.In你的情況,你的樓內設有商務邏輯需要在一個線程中運行,那麼使用的界面。

如果您有效地運行線程的更好方法,然後擴展線程。