當我們創建一個新線程並在run方法本身中啓動它時會發生什麼?當我在run方法內部或外部聲明線程時爲什麼會得到不同的行爲?以下是我嘗試的示例:java中的多線程運行方法中的start方法的行爲是什麼
class MyTDemo implements Runnable {
// If I declare t2 here, the program ends after some time
// Thread t2;
public void run()
{
// If I declare t2 here, the program never ends (until StackOverFlowException)
Thread t2;
System.out.println("in Run");
t2 = new Thread(this);
try{
t2.sleep(5000);
t2.start();
System.out.println("going out "+t2.isDaemon());
t2.sleep(5000);
t2.setDaemon(true);
}
catch(Exception e){System.out.println(e.getMessage());}
}
public static void main(String args[])
{
MyTDemo t = new MyTDemo();
Thread t1,t2;
t1 = new Thread(t);
t1.start();
System.out.println("End");
}
}
@assylias:問題不完整。 OP意味着他得到了不同的行爲,但沒有說出那是什麼行爲。 –
是的,我現在看到了@assylias。編輯澄清。代碼有點亂。請注意,「不清楚」意味着不清楚。 –