JAVA多线程捕获异常的问题
java吧
全部回复
仅看楼主
level 10
wyl0706 楼主
下面是学习如何捕获多线程异常的一个范例:
import java.util.concurrent.*;
class ExceptionThread2 implements Runnable {
public void run() {
Thread t = Thread.currentThread();
System.out.println("run() by " + t);
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
throw new RuntimeException();
}
}
class MyUncaughtExceptionHandler implements
Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.out.println("caught " + e);
}
}
class HandlerThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
System.out.println(this + " creating new Thread");
Thread t = new Thread(r);
System.out.println("created " + t);
t.setUncaughtExceptionHandler(
new MyUncaughtExceptionHandler());
System.out.println(
"eh = " + t.getUncaughtExceptionHandler());
return t;
}
}
public class CaptureUncaughtException {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool(
new HandlerThreadFactory());
exec.execute(new ExceptionThread2());
}
}
2016年04月17日 04点04分 1
level 10
wyl0706 楼主
2016年04月17日 04点04分 2
level 10
wyl0706 楼主
但奇怪的是,这个demo创建了两个线程,明明只有一个exec.execute(new ExceptionThread2());啊
谁知道是为什么?
2016年04月17日 04点04分 3
level 10
wyl0706 楼主
而且运行之后这个程序并没有结束,再输出:caught java.lang.RuntimeException之后也没有退出。为什么?
2016年04月17日 04点04分 4
level 1
我日,16年的帖子,还没人回复,你知道啥原因了吗?
2018年09月19日 11点09分 6
1