據說線程永遠不應該在構造函數中啓動,但我不確定this
參考在這種情況下如何轉義構造函數Test
。我查看了底層的Thread.java,我無法弄清楚。在構造函數中啓動線程
class Test {
static MyThread thread;
public Test() {
thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread {
public void run() {
//do stuff
}
}
感謝您的幫助。
thread = new MyThread();
會打電話Thread
超級構造函數:
public Thread() {
init(null, null, "Thread-" + nextThreadNum(), 0);
}
我沒有看到一個參考越來越遠。
使線程靜態是一個壞主意。 – SLaks
相關http://stackoverflow.com/questions/8057510/java-starting-a-new-thread-in-a-constructor – Tunaki