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.");
        }
    }
  • 相关阅读:
    python基础知识的重点面试题
    初入SG-UAP
    sg-uap常用注解介绍
    Git简介
    Docker 阿里云镜像加速
    Elasticsearch 读时分词、写时分词
    Java 显示调用隐式调用
    SecureFX中文目录乱码问题解决方案
    Linux 防火墙遇到的问题
    Docker Gitlib创建项目后仓库连接IP地址不一致问题(包括进入docker中容器命令及退出命令)
  • 原文地址:https://www.cnblogs.com/vectorli/p/5363271.html
Copyright © 2011-2022 走看看