gpt4 book ai didi

java - 为什么如果我们不使用 join() 多线程 C++ 程序会崩溃,而类似的 Java 程序不会

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:50 24 4
gpt4 key购买 nike

假设我们有以下 C++ 程序

void hello (){
std :: cout << "HELLO"<<std::endl ;
}

int main(){

std:: thread t(hello) ;
t.join() ;

}

如果我们不在这段代码中调用 join,我们的程序就会崩溃,因为主线程会在线程 t1 完成之前终止。但是如果我们在 Java 中有相同的程序,即使 main 不等待线程,程序也会正常执行。

public class HelloWorld {
public static void main(String[] args) {
Thread t = new Thread(new Hello());
t.start();

}

}

class Hello implements Runnable {

public void run() {

System.out.println("Hello") ;

}
}

那么为什么在 Java 中程序不会崩溃呢?即使 main 先完成,线程如何执行?

最佳答案

这很简单:与 C++ 相比,它在 main 完成后终止,Java 程序只有在所有(非守护进程)线程(包括 main)都完成时才结束(参见,对于例如,this oracle 线程文档):

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:

a. The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.

b. 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.

相比之下,C++ 将开始破坏具有静态存储持续时间的对象,如果分离的线程仍在运行并访问此类对象,则会产生未定义的行为(例如,参见 this C++ 标准草案关于程序终止):

3.6.3 Termination

Destructors ([class.dtor]) for initialized objects (that is, objects whose lifetime ([basic.life]) has begun) with static storage duration are called as a result of returning from main and as a result of calling std::exit ([support.start.term]).

关于java - 为什么如果我们不使用 join() 多线程 C++ 程序会崩溃,而类似的 Java 程序不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54207040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com