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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/uestcyms/article/details/84323121

进程与多线程

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

结论:

语言 主线程 子线程
C++ 挂死 挂死
Java 继续运行 继续运行

C++ code

#include <iostream>
#include <thread>
#include <chrono>

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
… …

猜你喜欢

转载自blog.csdn.net/uestcyms/article/details/84323121