假设我们有以下C++程序
void hello (){
std :: cout << "HELLO"<<std::endl ;
}
int main(){
std:: thread t(hello) ;
t.join() ;
}
Run Code Online (Sandbox Code Playgroud)
如果我们不调用此代码中的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") ;
}
}
Run Code Online (Sandbox Code Playgroud)
那么为什么在Java中程序不会崩溃?即使主要完成,线程如何执行?