我不明白啓動和運行線程之間的區別,我測試了這兩種方法並輸出相同的結果,首先我使用run()的組合並開始運行線程和他們做了同樣的功能如下:運行和啓動線程之間的區別
public class TestRunAndStart implements Runnable {
public void run() {
System.out.println("running");
}
public static void main(String[] args) {
Thread t = new Thread(new TestRunAndStart());
t.run();
t.run();
t.start();
}
}
輸出爲:
running
running
running
然後只見run()方法的的Javadoc表示: If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns
所以我試圖用run()方法,而不需要單獨運行的,如下所示:
public class TestRun extends Thread {
public void run(){
System.out.println("Running Normal Thread");
}
public static void main(String[]args){
TestRun TR=new TestRun();
TR.run();
}
}
,它也執行run()方法並打印Running Normal Thread
儘管它沒有獨立的Runnable構建!那麼什麼是兩種方法
它不是重複的! – naXa 2015-03-24 11:50:19
但是爲時已晚。但可能對別人有幫助。用「System.out」替換run方法的SOP語句。println(「正在運行的線程...」+ Thread.currentThread()。getName());「然後執行你的程序,你會看到不同的結果:輸出是」正在運行的線程... main running thread ... main 正在運行的線程... Thread-0「 – user320676 2016-08-12 06:47:10