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