2014-08-29 47 views
5

我正在學習Java中的多線程概念,在這裏我遇到了這個非常有趣的行爲。我正在嘗試各種創建線程的方式。現在的問題是我們延長Thread,而不是實現Runnable接口。Java中有趣的線程行爲

在附註中,我知道它實現了Runnable接口的完美OO感,而不是擴展Thread類,但對於此問題的目的,假設我們擴展了Thread類。

t是我的我的擴展Thread類的實例,我有一個代碼塊中是我的我的Thread類的run()方法中寫後臺執行。

它與t.start()在後臺完美運行,但我有點好奇,並調用t.run()方法。這段代碼在主線程中執行!

t.start()這樣做t.run()不是嗎?

+4

我相信你可以在這裏找到答案(這威力實際上打破你的面向對象的設計。): HTTP: //stackoverflow.com/questions/8579657/java-whats-the-difference-between-thread-start-and-runnable-run http://stackoverflow.com/questions/15841301/difference-between-running-and -starting-a-thread – 2014-08-29 09:49:37

+0

http:// stackoverflow。com/a/13134221/3436942告訴你簡單易懂的語言的區別。很多** t.start(); **正在創建/創建一個新線程,而** t.run(); **只是在主線程上調用它 – jbutler483 2014-08-29 09:51:02

回答

8

這就是班級所要做的。 t.start()實際上會啓動一個新線程,然後在該線程中調用run()。如果直接調用run(),則在當前線程中運行它。

public class Test implements Runnable() { 
    public void run() { System.out.println("test"); } 
} 

... 

public static void main(String...args) { 
    // this runs in the current thread 
    new Test().run(); 
    // this also runs in the current thread and is functionally the same as the above 
    new Thread(new Test()).run(); 
    // this starts a new thread, then calls run() on your Test instance in that new thread 
    new Thread(new Test()).start(); 
} 

這是打算的行爲。

+0

哇,真棒解釋!謝謝您的回答。 :) – avismara 2014-08-29 09:56:23

1

t.start()只是做它說的:啓動一個新的線程,執行run()的代碼部分。 t.run()是一個對象的函數調用,從當前工作線程(在你的情況下,主線程)。請注意:只有在調用線程函數start()時,纔會啓動一個新線程,否則,調用它的函數(start()除外)與在任何其他不同對象上調用普通函數相同。

+0

謝謝你的回答。 :) – avismara 2014-08-29 10:02:55

0

t.start()進行本地調用,以在新線程中實際執行run()方法。 t.run()僅在當前線程中執行run()

現在,

在一個側面說明,我知道,這是絕對OO意義上實現Runnable接口,而不是擴展Thread類

事實上,它使完美 OO感遵循這兩種方法(實現Runnable或擴展Thread)。從OO的角度來看,這並不是一件壞事。您通過實施獲得優勢的Runnable是,你可以讓你的類擴展另一個類

+0

s /主線程/當前線程/,AFAIK。 – DarkDust 2014-08-29 09:57:16

+0

我當時正在談論當前的情況。如果您打算將特性和功能添加到「線程」,那麼擴展「線程」類是有意義的。如果你只是想創建一個新的線程,實現'Runnable'類。 :) – avismara 2014-08-29 09:58:04

+0

@DarkDust - 我沒有得到你。 – TheLostMind 2014-08-29 09:58:37