简体   繁体   English

捕获由主线程中的工作线程创建的异常

[英]Catching exceptions created by worker threads in Main thread

How do we handle the Exceptions generated from threads started by ThreadPoolTaskExecutor in main thread? 我们如何处理由ThreadPoolTask​​Executor在主线程中启动的线程生成的异常?

public static void main(String[] args){
     ApplicationContext context =  new ClassPathXmlApplicationContext("applicationContext.xml");
     ThreadPoolTaskExecutor executer = (ThreadPoolTaskExecutor)context.getBean("taskExecutor_test");

     for(int i=0; i<5; i++){
        executer.execute(new RunnableImpl()); //If any of the thread create exception
     }

    //need to catch the exceptions here.
}

[like what we do with 'setUncaughtExceptionHandler' in normal Thread] [就像我们在普通线程中使用'setUncaughtExceptionHandler'所做的一样]

When submitting tasks to the ThreadPoolTaskExecutor , you're expecting those tasks to be run asynchronously, so your code can't catch and handle exceptions unless you block and wait for them to happen. 将任务提交给ThreadPoolTaskExecutor ,您期望这些任务是异步运行的,因此,除非阻塞并等待异常发生,否则您的代码将无法catch和处理异常。

To do this, use ThreadPoolTaskExecutor#submit(Runnable) which returns a Future . 为此,请使用ThreadPoolTaskExecutor#submit(Runnable)返回一个Future You can then call Future#get() to block the current thread and wait for either the task to complete or for an exception to be thrown (which completes (fails) the task). 然后,您可以调用Future#get()来阻止当前线程,并等待任务完成或引发异常(任务完成(失败))。 If it's a long running task, you can also poll for its completion with its Future#isDone() or the overloaded get(..) method. 如果它是一项长期运行的任务,则还可以使用其Future#isDone()或重载的get(..)方法来轮询其完成情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM