Java和C++多线程对比

Java和C++中都提供了多线程编程的方式,实现的方法也很相似。

其中的主要和区别有:

1.C++中子线程都是在主线程的运行都是在main()方法的生命周期中运行的,而Java的子线程的生命周期可以延续到main()方法的外面。

例如CPP

#include <iostream>
#include <thread>

using namespace std;

int main()
{
    cout << "Start main()" << endl;

    std::thread tr([]() {
        for (int i = 0; i < 100; i ++) {
            cout << "Child thread : " << i << endl;
        }
        cout << "Exiting child thread..." << endl;
    });

    tr.join();

    cout << "Exiting main() thread..." << endl;
    return 0;
}

启动线程之后必须要调用join()让线程正常退出,否则程序将会异常终止。

而在Java中,只需要调用start()方法启动线程,线程执行完成后由垃圾回收进行处理,不需要在主线程中等待子线程执行完成(也可以使用join()等待子线程完成)。

class NewThread1 extends Thread {
    NewThread1() {
        super("Demo Thread");
        System.out.println("Child thread: " + this);
        start();
    }

    @Override
    public void run() {
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println("Child Thread: " + i);
                Thread.sleep(50);
            }
        } catch (InterruptedException e) {
            System.out.println("Child Interrupted.");
        }
        System.out.println("Exiting child thread.");
    }
}
//NOTE:主线程退出之后子线程仍然可以继续运行
public class ExtendThread {
    public static void main(String[] args) {
        new NewThread1();
        try {
            for (int i = 5; i > 0; i--) {
                System.out.println("Main thread: " + i);
                Thread.sleep(10);
            }
        } catch (InterruptedException e) {
            System.out.println("Main thread interrupted");
        }
        System.out.println("Main thread exiting.");
    }
}

 

转载于:https://www.cnblogs.com/vectorli/p/5363271.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值