我有一个简单的java程序。创建一个主线程 (main()
) 并启动另一个线程 t
。
class T extends Thread{
@Override
public void run() {
while (true){
System.out.println("Inside thread");
}
}
}
public class Main {
public static void main(String[] args) {
Thread t = new T();
t.start();
//t.join();
System.out.println("end");
}
}
输出:
end
Inside thread
Inside thread
Inside thread
....
....
它无限打印 内部线程 。我不是在使用 join() 等待主线程中的子线程。打印 end 后主线程不应该退出吗?
更新:
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.
我找到了原因。第二点澄清了它。我假设所有子线程都将在主线程退出后终止(我错了)并且 JVM 应该关闭。
最佳答案
主线程已经退出。这是另一个还活着的线程。
关于java:为什么主线程等待子线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42515650/