我的代码如下所示:

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块,这是重复很多的代码)。

最佳答案

不,如果不使用try...catch块,则无法实现此目的,请参见jls


  如果找不到可以处理异常的catch子句,则
  当前线程(遇到异常的线程)是
  终止。




而且,我认为在缓存的线程池中终止线程不是问题,因为下次提交新任务时,将创建一个新线程来处理它。



如果确实很重要,并且您不想重复代码,则可以编写这样的包装器类:

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/

10-14 10:42