kim.zhang

风在前,无惧!


  • 首页

  • 标签42

  • 分类12

  • 归档94

  • 搜索

子线程异常处理.md

发表于 2020-08-10 更新于 2021-11-21 分类于 并发
本文字数: 2.2k 阅读时长 ≈ 2 分钟

栗子1:主线程无法捕获子线程抛出的异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class UnCaughtException {
public static void main(String[] args) {
try {
MyThread myThread = new MyThread();
new Thread(myThread, "thread-1").start();
new Thread(myThread, "thread-2").start();
new Thread(myThread, "thread-3").start();
new Thread(myThread, "thread-4").start();
} catch (RuntimeException e) {
System.out.println("主线程捕获了子线程抛出的异常");
}

}
}

class MyThread implements Runnable {

@Override
public void run() {
throw new RuntimeException("我是来自子线程的异常");
}
}

执行结果:

因为try..catch..只能捕获当前线程内抛出的异常。

1
2
3
4
5
6
7
8
9
10
11
12
Exception in thread "thread-1" Exception in thread "thread-4" Exception in thread "thread-2" Exception in thread "thread-3" java.lang.RuntimeException: 我是来自子线程的异常
at threadexception.MyThread.run(UnCaughtException.java:34)
at java.lang.Thread.run(Thread.java:748)
java.lang.RuntimeException: 我是来自子线程的异常
at threadexception.MyThread.run(UnCaughtException.java:34)
at java.lang.Thread.run(Thread.java:748)
java.lang.RuntimeException: 我是来自子线程的异常
at threadexception.MyThread.run(UnCaughtException.java:34)
at java.lang.Thread.run(Thread.java:748)
java.lang.RuntimeException: 我是来自子线程的异常
at threadexception.MyThread.run(UnCaughtException.java:34)
at java.lang.Thread.run(Thread.java:748)

栗子2:使用Thread类的UncaughtExceptionHandler接口实现全局捕获异常

1
2
3
4
5
6
7
// 自定义异常处理器,由于是函数式接口,可以使用Lambda表达式
public class UnCaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println(t.getName() + "发生了异常;" + e.getMessage());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class UnCaughtException {
public static void main(String[] args) {
// 设置默认的异常处理器
Thread.setDefaultUncaughtExceptionHandler(new UnCaughtExceptionHandler());
MyThread myThread = new MyThread();
new Thread(myThread, "thread-1").start();
new Thread(myThread, "thread-2").start();
new Thread(myThread, "thread-3").start();
new Thread(myThread, "thread-4").start();

}
}

class MyThread implements Runnable {

@Override
public void run() {
throw new RuntimeException("我是来自子线程的异常");
}
}

执行结果:

1
2
3
4
thread-1发生了异常;我是来自子线程的异常
thread-3发生了异常;我是来自子线程的异常
thread-2发生了异常;我是来自子线程的异常
thread-4发生了异常;我是来自子线程的异常

如何处理子线程出现的异常?

  • 在子线程内部try..catch..处理
  • 设置Thread默认的异常处理器,全局处理异常
一毛也是爱~
Kim.Zhang 微信支付

微信支付

# 并发基础,异常
创建线程的方式.md
Semaphore.md
  • 文章目录
  • 站点概览
Kim.Zhang

Kim.Zhang

且行且珍惜
94 日志
12 分类
42 标签
E-Mail Weibo
  1. 1. 栗子1:主线程无法捕获子线程抛出的异常
  2. 2. 栗子2:使用Thread类的UncaughtExceptionHandler接口实现全局捕获异常
  3. 3. 如何处理子线程出现的异常?
粵ICP备19091267号 © 2019 – 2022 Kim.Zhang | 629k | 9:32
本站总访问量 4 次 | 有 309 人看我的博客啦 |
博客全站共176.7k字
载入天数...载入时分秒...
0%