【发布时间】:2018-08-26 22:19:20
【问题描述】:
我的代码如下所示:
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 块除外,这是很多重复的代码)。
【问题讨论】:
标签: java multithreading exception-handling threadpool