在我的一个应用程序中,我正在使用ExecutorService该类创建一个固定的线程池并CountDownLatch等待线程完成.如果进程没有抛出任何异常,这工作正常.如果任何线程中发生异常,我需要停止所有正在运行的线程并将错误报告给主线程.任何人都可以帮我解决这个问题吗?
这是我用于执行多个线程的示例代码.
private void executeThreads()
{
int noOfThreads = 10;
ExecutorService executor = Executors.newFixedThreadPool(noOfThreads);
try
{
CountDownLatch latch = new CountDownLatch(noOfThreads);
for(int i=0; i< noOfThreads; i++){
executor.submit(new ThreadExecutor(latch));
}
latch.await();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
executor.shutDown();
}
}
Run Code Online (Sandbox Code Playgroud)
这是Executor类
public class ThreadExecutor implements Callable<String> {
CountDownLatch latch ;
public ThreadExecutor(CountDownLatch latch){
this.latch = latch;
}
@Override
public String call() throws Exception
{
doMyTask(); // process logic goes here!
this.latch.countDown();
return "Success";
}
Run Code Online (Sandbox Code Playgroud)
================================================== …