我之前阅读过一些 SO 问题和文档,但没有找到我的回复:
- 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 呢?
当我在 start()
join()
时发生了什么
有关信息,我正在使用:
- JVM:Java HotSpot(TM) 客户端 VM(20.45-b01,混合模式,共享)
- Java:版本 1.6.0_45,供应商 Sun Microsystems Inc.
阅读您的一些回复后更新
如果我理解,更好的实现应该是这样的:
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
最佳答案
isAlive() 的文档说:
A thread is alive if it has been started and has not yet died.
join() 的文档说:
Waits at most millis milliseconds for this thread to die
因此,在 join() 返回后,
- 线程已经死亡,isAlive() 将为 false
- 或者线程还没有死但是延迟已经过去,并且 isAlive() 可能为真。这是可能的,但可能性极小,因为线程有 5 秒的时间来完成打印到控制台的简单工作。
关于java - 这个线程能不能存活以及如何使用java.lang.Thread.join()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29774124/