java - 如何避免在没有 try catch 的情况下抛出异常时线程池中的线程死亡

标签 java multithreading exception threadpool

我的代码如下所示:

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/

相关文章:

java - 在 Android 3.1 上通过 USB 端口读取和写入数据

java - Eclipse Juno 插件项目中的 mysql jdbc 连接错误

java - asm 中的静态初始化程序

c# - 为什么我的 Draw() 和 Update() 方法没有被调用?

java - 如何告诉 Runnable 抛出 InterruptedException?

Java Happens-Before 和线程安全

c++ - 对 std::runtime_error 的 what() 函数的误解

ruby-on-rails-3 - Rspec 误报,因为在被测试的代码中拯救了失败异常

java - 构造函数不抛出新异常?

ruby-on-rails - rails : delete a flash message inside a custom error controller