我的代码如下所示:
public class ExceptionTest {
public static Logger log = LoggerFactory.getLogger(ExceptionTest.class);
public final static ThreadFactory factory = new ThreadFactory() {
@Override
public Thread newThread(Runnable target) {
final Thread thread = new Thread(target);
log.debug("Creating new worker thread");
thread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
log.error("Uncaught Exception", e);
}
});
return thread;
}
};
final static ExecutorService executor = Executors.newCachedThreadPool(factory);
public static void main(String[] args) {
executor.execute(new Runnable() {
@Override
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName());
int i = 1;
int j = 0;
System.out.println(i / j);
}
}
});
}
}
控制台只打印一次该消息。这意味着线程已经死亡。有没有其他方法可以防止线程死亡(除了 try catch
block ,这是很多重复的代码)。
最佳答案
不,不使用 try...catch
block 就无法实现此目的,请参阅 jls :
<小时/>If no catch clause that can handle an exception can be found, then the current thread (the thread that encountered the exception) is terminated.
而且,我不认为缓存线程池中线程的终止是一个问题,因为下次您提交新任务时,将创建一个新线程来处理它。
<小时/>如果它真的很重要,并且您不想重复代码,您可以编写如下包装类:
public class WrapperRunnable implements Runnable {
Runnable runnable;
public WrapperRunnable(Runnable runnable) {
this.runnable = runnable;
}
@Override
public void run() {
while (true) {
try {
runnable.run();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
并将WrapperRunnable
提交给执行器:
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
int i = 1;
int j = 0;
System.out.println(i / j);
}
};
WrapperRunnable wrapperRunnable = new WrapperRunnable(runnable);
executor.execute(wrapperRunnable);
关于java - 如何避免在没有 try catch 的情况下抛出异常时线程池中的线程死亡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49344618/