public class SousThread implements Runnable {
private int i;
public SousThread() {
this.i = 0;
}
@Override
public void run() {
while(true) {
System.out.println("I'm sousthread " + i++);
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class TestThread implements Runnable {
@Override
public void run() {
System.out.println("I'm thread");
SousThread st = new SousThread();
Thread td = new Thread(st);
td.start();
System.out.println("thread finished");
}
public static void main(String[] args) {
TestThread tt = new TestThread();
Thread td = new Thread(tt);
td.start();
System.out.println("main finished");
}
}
我正在尝试在线程 TestThread
中创建线程 SousThread
。 SousThread
是无限的。
令我惊讶的是,我得到了以下结果:
I'm thread
main finished
thread finished
I'm sousthread 0
I'm sousthread 1
I'm sousthread 2
I'm sousthread 3
I'm sousthread 4
I'm sousthread 5
...
...
这是否意味着方法main
已完成而线程尚未完成?这可能吗?这安全吗?如果没有,更好的方法是什么?
更新
因为这样的代码在 C++ 中不起作用。所以我只想知道代码在 Java 中是否可以正常运行,没有任何问题或风险。
最佳答案
这是well documented完全正常:
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:
- The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
- All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.
在您的情况下,虽然主线程已终止(通过 main()
返回隐式终止),但其他线程仍然处于 Activity 状态。除非您在某处调用 System.exit() 或将其他线程设置为守护线程,否则 JVM 将继续运行,直到所有线程都加入。
如果您希望所有线程在主线程存在之前终止,则需要 Thread.join()
他们。请注意Runtime.exit()
非常严厉地终止线程。线程是 not interrupted nor are their finalizers called ,所以这确实不安全。
关于java线程执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43009656/