目录
线程捕捉
demo
其他方法
只捕捉线程组异常
线程捕捉
有两种方法:一种捕捉指定的线程,一种是捕捉所有的线程
捕捉所有的线程
捕捉指定的线程
demo
m1
m2
Exception in thread "m2" java.lang.NullPointerException
at MyThread.run(Test.java:9)
线程:m1出现了异常
m1、m2都异常,只捕获m1
m1
m2
线程:m1出现了异常
线程:m2出现了异常
其他方法
使用Executors创建线程时,还可以在ThreadFactory中设置
ExecutorService exec = Executors.newCachedThreadPool(new ThreadFactory(){
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setUncaughtExceptionHandler(new MyUnchecckedExceptionhandler());
return thread;
}
});
利用线程池提交线程时返回的Feature引用
Future<Integer> future = executorService.submit(callable);
try {
Integer result = future.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
//4.处理捕获的线程异常
}
只捕捉线程组异常
public class Test
{
public static void main(String[] args) {
//线程组
MyGroup group = new MyGroup("My组");
MyThread m = new MyThread(group,"线程m");
//对象
// m.setUncaughtExceptionHandler(new ObjectUncaughtExceptionHandler()) ;
//类
// MyThread.setDefaultUncaughtExceptionHandler(new StateUncaughtExceptionHandler()) ;
m.start() ;
}
}
Exception in thread "线程m" java.lang.NumberFormatException: For input string: "a"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.qin.test2.MyThread.run(Test.java:43)
java.lang.NumberFormatException: For input string: "a"
线程组的异常处理
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at com.qin.test2.MyThread.run(Test.java:43)