zoukankan      html  css  js  c++  java
  • 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.");
        }
    }
  • 相关阅读:
    mysql外键(FOREIGNKEY)使用介绍
    MYSQL数据库-约束
    mysql探究之null与not null
    爬虫
    http://blog.csdn.net/w_e_i_/article/details/70766035
    Python 3.5安装 pymysql 模块
    Python 3.5 连接Mysql数据库(pymysql 方式)
    hdu Bone Collector
    hdu City Game
    hdu Largest Rectangle in a Histogram
  • 原文地址:https://www.cnblogs.com/vectorli/p/5363271.html
Copyright © 2011-2022 走看看