我看過之前的一些SO問題和文檔,但沒有找到我的迴應:這個線程可以活着,如何使用java.lang.Thread.join()方法
- How long a thread will be alive in java?
- When is a Java thread alive?
- http://journals.ecs.soton.ac.uk/java/tutorial/java/threads/states.html
所以......
public class MyThread extends Thread {
public MyThread() {
this.setName("MyThread-" + System.currentTimeMillis());
this.start();
}
public MyThread(long millis) throws InterruptedException {
this.setName("MyThread-" + System.currentTimeMillis());
this.join(millis);
this.start();
}
@Override
public void run() {
System.out.println("I am running...");
// This thread does not sleep... no Thread.sleep() in run method.
// Do some things like requesting a database
// Database response happens in less time that the timeout
}
}
public class MyClass {
public MyClass(){
for (int i = 0; i < 5; i++) {
Thread t1 = new MyThread();
t1.join(5000);
if (t1.isAlive()) {
System.out.println("I'm alive");
// do some things
} else {
System.out.println("I'm not alive");
}
Thread t2 = new MyThread(5000);
if (t2.isAlive()) {
System.out.println("I'm alive");
// do some things
} else {
System.out.println("I'm not alive");
}
}
}
}
看起來不可能,但t1
之一可以活着嗎? t2怎麼樣? 發生了什麼,當我打電話join()
後start()
有關信息,我使用:
- JVM:Java的熱點(TM)客戶端虛擬機(20.45-B01,混合模式,共享)
- 的Java:版本1.6.0_45,供應商Sun微系統公司
更新閱讀一些您的回答後
如果我的理解,更好的實現將是這樣的:
public class MyThread extends Thread {
public MyThread() {
super("MyThread-" + System.currentTimeMillis());
}
@Override
public void run() {
System.out.println("I am running...");
// This thread does not sleep... no Thread.sleep() in run method.
// Do some things like requesting a database
// Database response happens in less time that the timeout
}
}
public class MyClass {
public MyClass(){
for (int i = 0; i < 5; i++) {
Thread t1 = new MyThread();
t1.start();
t1.join(5000);
if (t1.isAlive()) {
System.out.println("I'm alive");
// do some things
} else {
System.out.println("I'm not alive");
}
}
}
}
這兩種看法都幫了我很多:https://stackoverflow.com/a/29775219/1312547和https://stackoverflow.com/a/29775083/1312547
兩個筆記,雖然他們沒有回答你的問題:首先,你爲什麼要在構造函數中啓動之前加入線程呢?其次,你實際上不應該從它的構造函數中啓動一個線程。原因有點微妙,但基本上一堆方便合理的線程保證會在窗口出現,如果你這樣做的話。你應該總是先構建它,然後啓動它。 – yshavit
[建議實現Runnable而不是擴展線程](http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread)。我建議你先在代碼中遵循多線程的良好實踐,然後重寫你的測試。 – m0skit0
同上yshavit說:在構造函數中調用'this.start()'是_Bad Idea_。它可能允許新線程的run()方法查看處於未初始化狀態的Thread對象。將start()調用移動到MyClass()構造函數中。調用.start()之前調用.join()?您是否閱讀過文檔? –