小编Ach*_*u S的帖子

如果其中一个抛出异常,如何停止所有正在运行的线程?

在我的一个应用程序中,我正在使用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)

================================================== …

java multithreading

11
推荐指数
2
解决办法
9009
查看次数

标签 统计

java ×1

multithreading ×1