多线程中子线程抛出异常后,如何表现

进程与多线程

多线程中一个线程抛出异常(不捕获);主线程及其他子线程如何表现

  • 结论
语言 主线程 子线程
C++ 挂死 挂死
Java 继续运行 继续运行
  • 原因
    java:存在用户线程(User Thread)和守护线程(Daemon Thread),当所有用户线程都退出了,守护线程退出,进而应用程序退出;这就是为什么"main线程"退出后,其他线程还正在运行。也是其他"子线程"被异常终止了或者退出了,其他线程正常运行。

    c++:main属于主进程,当子线程抛出异常时,最后抛到主线程中,导致主进程crash,进而结束应用程序,相应的Thread被销毁(thread对象被销毁)。

C++ code

#include 
#include 
#include 

void thread1_func() {
    int i = 0;
    while(true) {
        std::this_thread::sleep_for (std::chrono::seconds(1));
        std::cout << "thread1 i: " << i++ << "\n";
        if (i == 3) {
            throw 1;
        }
    }
}

void thread2_func() {
    int i = 0;
    while(true) {
        std::this_thread::sleep_for (std::chrono::seconds(1));
        std::cout << "thread2 i: " << i++ << "\n";
    }
}


int main() {
    std::cout << "Main thread start:spawning 2 threads... \n";
    std::thread t1 (thread1_func);
    std::thread t2 (thread2_func);

    t1.join();
    t2.join();

    std::cout << "Main thread end\n";
    return 0;
}

运行结果:

Main thread start:spawning 2 threads…
thread1 i: thread2 i: 00
thread1 i: 1
thread2 i: 1
thread1 i: 2
thread2 i: 2
terminate called after throwing an instance of ‘int’
Aborted (core dumped)

java代码:

public class ThreadDemo {

	public static void main(String[] args) {

		System.out.println("Main Thread start");

		// TODO Auto-generated method stub
		Thread t1 = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				int i = 0;
				while(true) {
					System.out.println("Thread1 i: "+(i++));
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					if (i == 3) {
						throw new RuntimeException();
					}
				}
			}
		});

		Thread t2 = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				int i = 0;
				while(true) {
					System.out.println("Thread2 i: "+(i++));
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});

		t2.start();
		t1.start();

		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Main Thread end");

	}

}

运行结果:

Thread2 i: 1
Main Thread end
Thread1 i: 1
Thread2 i: 2
Thread1 i: 2
Thread2 i: 3
Exception in thread “Thread-0” java.lang.RuntimeException
at ThreadDemo$1.run(ThreadDemo.java:26)
at java.lang.Thread.run(Unknown Source)
Thread2 i: 4
Thread2 i: 5
Thread2 i: 6
Thread2 i: 7
Thread2 i: 8
Thread2 i: 9
… …

你可能感兴趣的:(Java,C/C++)