小编Had*_*dev的帖子

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

假设我们有以下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中程序不会崩溃?即使主要完成,线程如何执行?

c++ java multithreading runnable

1
推荐指数
1
解决办法
293
查看次数

标签 统计

c++ ×1

java ×1

multithreading ×1

runnable ×1