【发布时间】:2015-04-21 13:49:23
【问题描述】:
我之前读过一些 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
【问题讨论】:
-
两个注释,虽然它们没有回答你的问题:首先,你为什么在构造函数中开始之前加入线程?其次,您实际上不应该从其构造函数中启动线程。原因有点微妙,但如果你这样做,基本上一堆方便推理的线程保证就会消失。您应该始终先构建它,然后再启动它。
-
It is recommended to implement Runnable instead of extend Thread。我建议您首先在代码中遵循多线程的良好实践,然后重写您的测试。
-
同上 yshavit 所说的:从构造函数中调用
this.start()是一个坏主意。它可能允许新线程的 run() 方法看到处于未初始化状态的 Thread 对象。将 start() 调用移动到 MyClass() 构造函数中。并在调用 .start() 之前调用 .join()?你读过文档吗? -
@jameslarge 没有提到他甚至没有打电话给
super()。 -
通过您的修改,您现在的问题究竟是什么?你到底想达到什么目的?
标签: java multithreading jdk1.6