Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

10个方法开启10个线程,其中有一个方法报错时中止其他方法 使用java伪代码写出来

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b’s answer.
  1. User

    10个方法开启10个线程,其中有一个方法报错时中止其他方法 使用java伪代码写出来

  2. Claude Assistant

    这里提供一个使用 ExecutorService 和 CompletableFuture 的解决方案:

    import java.util.concurrent.*;
    import java.util.List;
    import java.util.ArrayList;
    
    public class ThreadManager {
        
        public void executeWithFailFast() {
            ExecutorService executor = Executors.newFixedThreadPool(10);
            List<CompletableFuture<Void>> futures = new ArrayList<>();
            
            try {
                // 创建10个异步任务
                for (int i = 0; i < 10; i++) {
                    final int taskId = i;
                    CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                        executeMethod(taskId);
                    }, executor);
                    futures.add(future);
                }
                
                // 等待所有任务完成,任何一个失败都会抛出异常
                CompletableFuture<Void> allTasks = CompletableFuture.allOf(
                    futures.toArray(new CompletableFuture[0])
                );
                
                allTasks.get(); // 阻塞等待,如果有异常会抛出
                
            } catch (Exception e) {
                System.out.println("检测到异常,正在中止所有任务...");
                
                // 取消所有未完成的任务
                for (CompletableFuture<Void> future : futures) {
                    future.cancel(true);
                }
                
                // 立即关闭线程池
                executor.shutdownNow();
                
                throw new RuntimeException("任务执行失败", e);
            } finally {
                if (!executor.isShutdown()) {
                    executor.shutdown();
                }
            }
        }
        
        // 模拟10个不同的方法
        private void executeMethod(int methodId) {
            try {
                System.out.println("方法 " + methodId + " 开始执行");
                
                // 模拟业务逻辑
                Thread.sleep(2000 + (int)(Math.random() * 3000));
                
                // 模拟某个方法报错
                if (methodId == 3) {
                    throw new RuntimeException("方法 " + methodId + " 执行失败");
                }
                
                System.out.println("方法 " + methodId + " 执行完成");
                
            } catch (InterruptedException e) {
                System.out.println("方法 " + methodId + " 被中断");
                Thread.currentThread().interrupt();
            }
        }
    }
    

    另一种使用 CountDownLatch 和共享状态的方案:

    import java.util.concurrent.*;
    import java.util.concurrent.atomic.AtomicBoolean;
    
    public class ThreadManagerWithLatch {
        private final AtomicBoolean hasError = new AtomicBoolean(false);
        private final CountDownLatch latch = new CountDownLatch(10);
        
        public void executeWithSharedState() {
            ExecutorService executor = Executors.newFixedThreadPool(10);
            
            try {
                // 启动10个任务
                for (int i = 0; i < 10; i++) {
                    final int taskId = i;
                    executor.submit(() -> {
                        try {
                            // 检查是否已有错误发生
                            if (hasError.get()) {
                                return;
                            }
                            
                            executeMethodWithCheck(taskId);
                            
                        } catch (Exception e) {
                            System.out.println("方法 " + taskId + " 发生错误: " + e.getMessage());
                            hasError.set(true); // 设置错误标志
                            
                            // 中断其他线程
                            executor.shutdownNow();
                        } finally {
                            latch.countDown();
                        }
                    });
                }
                
                // 等待所有任务完成或出错
                latch.await();
                
                if (hasError.get()) {
                    throw new RuntimeException("执行过程中发生错误");
                }
                
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("执行被中断", e);
            } finally {
                executor.shutdown();
            }
        }
        
        private void executeMethodWithCheck(int methodId) {
            try {
                System.out.println("方法 " + methodId + " 开始执行");
                
                for (int i = 0; i < 50; i++) { // 分段检查
                    if (hasError.get()) {
                        System.out.println("方法 " + methodId + " 检测到错误,提前退出");
                        return;
                    }
                    Thread.sleep(100); // 模拟工作
                }
                
                // 模拟某个方法报错
                if (methodId == 5) {
                    throw new RuntimeException("方法 " + methodId + " 业务逻辑错误");
                }
                
                System.out.println("方法 " + methodId + " 执行完成");
                
            } catch (InterruptedException e) {
                System.out.println("方法 " + methodId + " 被中断");
                Thread.currentThread().interrupt();
            }
        }
    }
    

    第一种方案使用 CompletableFuture.allOf() 来监控所有任务,任何一个失败都会导致整体失败并取消其他任务。第二种方案使用共享的 AtomicBoolean 状态来让各个线程互相感知错误状态,并主动退出执行。

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.