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.");
    }
}

 

posted @ 2016-04-07 13:56  Jax.Li  阅读(2943)  评论(0编辑  收藏  举报