如何在父线程中捕获来自子线程的异常呢

方法一:子线程中try... catch...

方法二:为线程设置异常处理器UncaughtExceptionHandler

(异常处理也是在子线程中执行,相当于在子线程中加上了一个异常拦截器,可以使用下面的程序验证)

(1)Thread.setUncaughtExceptionHandler设置当前线程的异常处理器

(2)Thread.setDefaultUncaughtExceptionHandler为整个程序设置默认的异常处理器

(3)new Thread(new ThreadTest() ,new runable{})时传入 ThreadGroup

方法三,通过Future的get方法捕获子线程异常

 

import java.util.concurrent.*;

public class ThreadTest extends ThreadGroup{

    private ThreadTest(){
super("ThreadTest");
} public static void main(String[] args) { System.out.println(Thread.currentThread().getId()); Thread t1=new Thread(new ThreadTest(),new Runnable() {//传入继承ThreadGroup的类对象
@Override
public void run() { try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} if (1==1){
throw new NullPointerException("111");
}
}
});
t1.start(); /*ExecutorService executorService = Executors.newFixedThreadPool(8);
Future future = executorService.submit(()->{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} if (1==1){
throw new NullPointerException("111");
}
return 1;
}); try {
future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) { //e.getCause().printStackTrace();
e.printStackTrace();
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
executorService.shutdownNow();*/ } public void uncaughtException(Thread thread, Throwable exception)
{
/**
* 当线程抛出unckecked异常时,系统会自动调用该函数,但是是在抛出异常的线程内执行*/
System.out.println(Thread.currentThread().getId());
System.out.println(thread.getId());
exception.printStackTrace();//example, print stack trace
}
}

线程池阻塞方法的使用  future.get()

1.LockSupport.park()消费一个信号量,会一直阻塞,LockSupport.park(thread)增加一个信号量

2.UNSAFE.park(false, 0L) 消费一个信号量 会一直阻塞 UNSAFE.unpark(thread) 增加一个信号量

3.和wait,notify(),notifyAll()相比的优点

3.1 park 和 unpark无先后顺序 而wait,notify(),notifyAll() 有严格顺序

3.2 park 和 unpark

最新文章

  1. HTML 网页特效CSS大全
  2. centos7 安装redis 开机启动
  3. C#可扩展编程之MEF学习笔记(四):见证奇迹的时刻
  4. SVN 使用锁实现独占式签出
  5. 分布式日志2 用redis的队列写日志
  6. SAP ALV标准范例程序介绍
  7. Java继承中属性、方法和对象的关系
  8. scp命令报错-bash: scp: command not found
  9. 如何使用第三方webservice
  10. IDEA jsp模板
  11. 从0开始构建你的api网关--Spring Cloud Gateway网关实战及原理解析
  12. leecode第二百三十六题(二叉树的最近公共祖先)
  13. strchr()
  14. [ 高危 ] hash碰撞DOS漏洞
  15. php ldap
  16. Retrofit/OkHttp API接口加固技术实践(下)
  17. WinForm窗体下Excel的导入
  18. kvo的observationInfo
  19. 网摘关于BarCodeControl控件
  20. python程序设计——面向对象程序设计:属性

热门文章

  1. windows系统使用sketch设计的设计稿
  2. Python中pip的使用
  3. ReviewBoard使用:添加SVN
  4. jQuery里ready方法用原生js实现原理
  5. 将用户名密码邮箱制成表格,以用户名为q结束
  6. Highcharts中文帮助文档
  7. 【PAT甲级】1116 Come on! Let's C (20分)
  8. dojo - 相关教程
  9. Hibernate:对象关系映射(一对一,一对多,多对一,多对多)
  10. Codeforces Round #609 (Div. 2) A-E简要题解