ClaudeAgent】并发-后台任务

发布时间:2026/7/18 4:18:56

ClaudeAgent】并发-后台任务
Java实现代码javapublic class BackgroundTasksSystem { // --- 配置 --- private static final Path WORKDIR Paths.get(System.getProperty(user.dir)); private static final Gson gson new GsonBuilder().setPrettyPrinting().create(); // --- 后台任务管理器 --- static class BackgroundManager { // 任务存储 private final MapString, TaskInfo tasks new ConcurrentHashMap(); // 通知队列 private final QueueTaskNotification notificationQueue new ConcurrentLinkedQueue(); // 任务 ID 生成器 private final AtomicInteger taskIdCounter new AtomicInteger(1); // 锁 private final Object lock new Object(); static class TaskInfo { String taskId; String status; // running, completed, timeout, error String result; String command; long startTime; Thread thread; // 关联的执行线程 } static class TaskNotification { String taskId; String status; String command; String result; } /** * 启动后台任务 * 立即返回任务 ID不等待命令完成 */ public String run(String command) { String taskId task_ taskIdCounter.getAndIncrement(); TaskInfo task new TaskInfo(taskId, command); tasks.put(taskId, task); // 创建并启动后台线程 Thread thread new Thread(() - executeTask(task), BackgroundTask- taskId); thread.setDaemon(true); task.thread thread; thread.start(); // 立即返回不阻塞 return String.format(Background task %s started: %s, taskId, command.substring(0, Math.min(command.length(), 80))); } /** * 线程目标执行子进程捕获输出推送结果到队列 */ private void executeTask(TaskInfo task) { String output; String status; try { ProcessBuilder pb new ProcessBuilder(bash, -c, task.command); pb.directory(WORKDIR.toFile()); pb.redirectErrorStream(true); Process process pb.start(); boolean finished process.waitFor(300, TimeUnit.SECONDS); // 5分钟超时 if (!finished) { process.destroy(); output Error: Timeout (300s); status timeout; } else { output new String(process.getInputStream().readAllBytes()).trim(); status completed; } } catch (Exception e) { output Error: e.getMessage(); status error; } // 更新任务状态 task.status status; task.result output.isEmpty() ? (no output) : output.substring(0, Math.min(output.length(), 50000)); // 添加通知到队列 synchronized (lock) { notificationQueue.offer(new TaskNotification( task.taskId, status, task.command.substring(0, Math.min(task.command.length(), 80)), task.result.substring(0, Math.min(task.result.length(), 500)) )); } } /** * 检查任务状态 * 如果指定 taskId检查单个任务否则列出所有任务 */ public String check(String taskId) { if (taskId ! null !taskId.isEmpty()) { TaskInfo task tasks.get(taskId); if (task null) { return Error: Unknown task taskId; } return String.format([%s] %s\n%s, task.status, task.command.substring(0, Math.min(task.command.length(), 60)), task.result ! null ? task.result : (running)); } else { StringBuilder sb new StringBuilder(); for (Map.EntryString, TaskInfo entry : tasks.entrySet()) { TaskInfo task entry.getValue(); sb.append(String.format(%s: [%s] %s\n, task.taskId, task.status, task.command.substring(0, Math.min(task.command.length(), 60)))); } return sb.length() 0 ? sb.toString().trim() : No background tasks.; } } /** * 清空通知队列并返回所有待处理的通知 */ public ListTaskNotification drainNotifications() { synchronized (lock) { ListTaskNotification notifications new ArrayList(); while (!notificationQueue.isEmpty()) { notifications.add(notificationQueue.poll()); } return notifications; } } /** * 获取所有任务 */ public MapString, TaskInfo getAllTasks() { return new HashMap(tasks); } } // 初始化后台管理器 private static final BackgroundManager BG_MANAGER new BackgroundManager(); // --- 工具枚举 --- public enum ToolType { BASH(bash, Run a shell command (blocking).), READ_FILE(read_file, Read file contents.), WRITE_FILE(write_file, Write content to file.), EDIT_FILE(edit_file, Replace exact text in file.), BACKGROUND_RUN(background_run, Run command in background thread. Returns task_id immediately.), // 新增 CHECK_BACKGROUND(check_background, Check background task status. Omit task_id to list all.); // 新增 public final String name; public final String description; ToolType(String name, String description) { this.name name; this.description description; } } // --- 工具处理器映射 --- private static final MapString, ToolExecutor TOOL_HANDLERS new HashMap(); static { // ... 省略基础工具注册 // 后台任务工具 TOOL_HANDLERS.put(ToolType.BACKGROUND_RUN.name, args - { String command (String) args.get(command); return BG_MANAGER.run(command); }); TOOL_HANDLERS.put(ToolType.CHECK_BACKGROUND.name, args - { String taskId (String) args.get(task_id); return BG_MANAGER.check(taskId); }); } // ... 省略相同的工具实现 // --- Agent 主循环集成后台任务通知--- public static void agentLoop(ListMapString, Object messages) { while (true) { try { // 在 LLM 调用前检查后台通知 ListBackgroundManager.TaskNotification notifications BG_MANAGER.drainNotifications(); if (!notifications.isEmpty() !messages.isEmpty()) { StringBuilder notifText new StringBuilder(); notifText.append(background-results\n); for (BackgroundManager.TaskNotification notif : notifications) { notifText.append(String.format([bg:%s] %s: %s\n, notif.taskId, notif.status, notif.result)); } notifText.append(/background-results); messages.add(Map.of( role, user, content, notifText.toString() )); messages.add(Map.of( role, assistant, content, Noted background results. )); // 异步结果注入将后台任务结果插入到对话中 // 结构化格式用XML标签包裹便于LLM解析 } // 显示当前活动任务 MapString, BackgroundManager.TaskInfo activeTasks BG_MANAGER.getAllTasks(); int runningTasks (int) activeTasks.values().stream() .filter(t - running.equals(t.status)) .count(); if (runningTasks 0) { System.out.printf([Active background tasks: %d]\n, runningTasks); } // ... 省略相同的 LLM 调用和工具执行逻辑 } catch (Exception e) { System.err.println(Error in agent loop: e.getMessage()); e.printStackTrace(); return; } } } }这段代码引入了后台任务系统解决了 Agent 在执行长时间任务时的阻塞问题关键洞察Agent 可以在命令执行时继续工作而不是被阻塞。异步任务处理架构核心思想从同步阻塞的任务执行升级为异步非阻塞的并发处理让Agent能够同时处理多个耗时任务实现并行计算能力大幅提升效率和响应性。java// 后台任务管理器 - 异步执行引擎 static class BackgroundManager { // 任务存储 private final MapString, TaskInfo tasks new ConcurrentHashMap(); // 通知队列 private final QueueTaskNotification notificationQueue new ConcurrentLinkedQueue(); // 任务 ID 生成器 private final AtomicInteger taskIdCounter new AtomicInteger(1); // 并发安全使用线程安全集合 // 异步通信通过队列传递任务结果 // 唯一标识自动生成任务ID }解耦执行任务提交和执行分离立即返回控制权并发管理多个后台任务可以同时运行结果异步收集通过队列机制收集完成的任务结果线程安全使用并发集合确保多线程安全任务信息结构设计java// 任务信息实体 static class TaskInfo { String taskId; // 唯一标识 String status; // 状态running, completed, timeout, error String result; // 执行结果 String command; // 执行的命令 long startTime; // 开始时间 Thread thread; // 关联的执行线程 // 完整状态跟踪从启动到完成的全生命周期 // 线程关联可以控制或监控执行线程 // 时间戳支持超时和性能分析 } // 任务通知实体 static class TaskNotification { String taskId; String status; String command; String result; // 轻量传输只包含必要信息 // 结构化易于解析和处理 // 结果截断避免过大的通知消息 }状态驱动明确的任务状态生命周期结果持久任务结果可以多次查询线程管理可以跟踪和控制执行线程事件驱动通过通知机制传递完成事件异步任务启动机制java/** * 启动后台任务 * 立即返回任务 ID不等待命令完成 */ public String run(String command) { String taskId task_ taskIdCounter.getAndIncrement(); TaskInfo task new TaskInfo(taskId, command); tasks.put(taskId, task); // 创建并启动后台线程 Thread thread new Thread(() - executeTask(task), BackgroundTask- taskId); thread.setDaemon(true); // 守护线程不会阻止JVM退出 task.thread thread; thread.start(); // 立即返回不阻塞调用者 return String.format(Background task %s started: %s, taskId, command.substring(0, Math.min(command.length(), 80))); // 异步启动立即返回任务ID不等待命令完成 // 守护线程不会阻止程序正常退出 // 线程命名便于调试和监控 }立即返回不阻塞主线程立即返回控制权守护线程后台任务不会阻止JVM退出资源管理线程自动清理避免内存泄漏友好反馈返回任务ID和简化的命令描述任务执行与结果收集java/** * 线程目标执行子进程捕获输出推送结果到队列 */ private void executeTask(TaskInfo task) { String output; String status; try { ProcessBuilder pb new ProcessBuilder(bash, -c, task.command); pb.directory(WORKDIR.toFile()); pb.redirectErrorStream(true); Process process pb.start(); boolean finished process.waitFor(300, TimeUnit.SECONDS); // 5分钟超时 if (!finished) { process.destroy(); output Error: Timeout (300s); status timeout; } else { output new String(process.getInputStream().readAllBytes()).trim(); status completed; } } catch (Exception e) { output Error: e.getMessage(); status error; } // 更新任务状态 task.status status; task.result output.isEmpty() ? (no output) : output.substring(0, Math.min(output.length(), 50000)); // 添加通知到队列 synchronized (lock) { notificationQueue.offer(new TaskNotification( task.taskId, status, task.command.substring(0, Math.min(task.command.length(), 80)), task.result.substring(0, Math.min(task.result.length(), 500)) )); } }超时保护防止长时间运行的任务阻塞异常安全全面捕获执行异常内存管理截断大结果避免内存溢出事件驱动完成后立即通知主线程智能通知注入机制java// 在 LLM 调用前检查后台通知 ListBackgroundManager.TaskNotification notifications BG_MANAGER.drainNotifications(); if (!notifications.isEmpty() !messages.isEmpty()) { StringBuilder notifText new StringBuilder(); notifText.append(background-results\n); for (BackgroundManager.TaskNotification notif : notifications) { notifText.append(String.format([bg:%s] %s: %s\n, notif.taskId, notif.status, notif.result)); } notifText.append(/background-results); messages.add(Map.of( role, user, content, notifText.toString() )); messages.add(Map.of( role, assistant, content, Noted background results. )); // 自动注入自动将后台结果插入到对话中 // 结构化格式XML标签明确标识内容类型 // 对话完整添加assistant确认保持对话结构 // 时机智能在LLM调用前插入确保LLM能看到最新结果 }自动同步后台结果自动同步到主对话结构化格式便于LLM识别和解析对话集成无缝集成到现有对话流时机优化在决策前注入确保信息及时性工具集成架构java// 后台任务工具集 public enum ToolType { BACKGROUND_RUN(background_run, Run command in background thread. Returns task_id immediately.), CHECK_BACKGROUND(check_background, Check background task status. Omit task_id to list all.); // 异步执行立即返回不阻塞 // 状态查询支持单个和批量查询 // 语义清晰工具名明确表示异步特性 } // 工具处理器映射 TOOL_HANDLERS.put(ToolType.BACKGROUND_RUN.name, args - { String command (String) args.get(command); return BG_MANAGER.run(command); // 委托执行将命令转交给后台管理器 // 立即返回不等待任务完成 }); TOOL_HANDLERS.put(ToolType.CHECK_BACKGROUND.name, args - { String taskId (String) args.get(task_id); return BG_MANAGER.check(taskId); // 灵活查询支持单任务详查和列表概览 });接口统一与同步工具相同的调用方式异步语义工具名明确区分同步/异步灵活查询支持多种查询方式无缝集成与现有工具系统完全兼容架构演进与价值从 ContextCompactSystem 到 BackgroundTasksSystem 的升级维度ContextCompactSystemBackgroundTasksSystem执行模式同步串行异步并行吞吐量一次一个任务并发多个任务响应性阻塞等待立即响应资源利用单线程多线程并发任务类型短任务为主长短任务混合

相关新闻

为什么不要做万能产品

为什么不要做万能产品

2026/7/10 20:42:59

很多产品一开始都有一个危险冲动:能不能做成万能工具?既能写文案,又能做图,又能分析数据,还能管理项目、生成报告、自动发布、团队协作。听起来市场更大,用户更多,机会更多。 但早期产品最怕的…

FastCAE Agent 与 Skill 体系应用 | 面向主流AI编程工具的配置·使用·成效指南

FastCAE Agent 与 Skill 体系应用 | 面向主流AI编程工具的配置·使用·成效指南

2026/7/8 7:03:57

一 为什么需要 Agent 与 Skill?在工业软件开发中,CAE(计算机辅助工程)领域代码量庞大、架构分层复杂、规范约束严格。传统 AI 编程助手面对此类项目时,往往只能给出泛化建议,无法深入理解项目的目录结构、命…

CRM管理系统有哪些?2026年高性价比选型指南

CRM管理系统有哪些?2026年高性价比选型指南

2026/7/10 17:31:44

很多企业在挑选 CRM 时,习惯先看每家的报价单,比完单价比折扣,最后选一个 "看起来最便宜" 的方案。但我们接触过的大量真实案例显示:约 60% 的企业在 CRM 上线后的第三年,实际支出会超出最初预算的 40% 以上…

Python Selenium自动化抢票脚本实战:从环境搭建到风控对抗

Python Selenium自动化抢票脚本实战:从环境搭建到风控对抗

2026/7/18 4:12:20

1. 项目概述与核心思路又到了一票难求的演唱会季,看着心仪的歌手开票,手速和网速却总是不给力,是不是感觉特别无力?作为一名常年混迹在技术圈和抢票一线的“老手”,我深知手动抢票的辛酸。今天,我就来聊聊如…

软件测试面试题

软件测试面试题

2026/7/18 4:12:20

测试基础 测试流程 需求分析-需求评审-需求确定-开发编写设计文档-概要设计和详细设计-编写代码并自测-提交测试 需求分析-需求评审-需求确定-编写测试计划-编写测试用例-用例评审-部署环境-执行测试-提交bug并跟踪bug-开发修改-回归测试-测试通过-发布上线 测试流程的时间分…

招投标合规避坑指南:为什么流程透明比低价中标更重要

招投标合规避坑指南:为什么流程透明比低价中标更重要

2026/7/18 4:12:20

一、招投标高频合规雷区,很多企业都踩过不少企业做招投标,总把重心放在压低采购价格上,却忽视了流程合规的重要性。事实上,很多采购纠纷、审计问题,都不是出在中标价格上,而是栽在流程不规范里。三类高频合…

ARM64交叉编译实战:从X86到RK3399Pro的C++程序移植指南

ARM64交叉编译实战:从X86到RK3399Pro的C++程序移植指南

2026/7/18 4:12:20

1. 项目概述:为什么需要跨架构移植?如果你手头有一个在X86电脑上跑得好好的C程序,现在想让它在一块RK3399Pro开发板上运行,你可能会发现直接拷贝过去根本行不通。这不是程序逻辑有错,而是因为你的电脑和这块开发板&…

Tiva™ EEPROM寄存器配置与嵌入式存储实战指南

Tiva™ EEPROM寄存器配置与嵌入式存储实战指南

2026/7/18 4:12:20

1. 项目概述:EEPROM在嵌入式系统中的核心角色在嵌入式系统开发中,我们经常需要一种能够“记住”关键信息的存储器。比如,一个智能温控器需要记住用户设定的温度偏好,一个工业传感器需要保存校准系数,一个消费电子设备需…

OpenClaw本地部署与飞书集成实践指南

OpenClaw本地部署与飞书集成实践指南

2026/7/18 4:02:19

1. 为什么我拖了一个多月才开始用OpenClaw? 作为技术从业者,我向来对新工具保持敏锐。但当OpenClaw这个号称"个人AI操作系统"的项目出现时,我却反常地观望了整整37天。这种迟疑背后,是三个关键考量: 1.1 本…

Unity游戏文本翻译架构深度解析:XUnity.AutoTranslator的技术实现与工程实践

Unity游戏文本翻译架构深度解析:XUnity.AutoTranslator的技术实现与工程实践

2026/7/17 10:50:47

Unity游戏文本翻译架构深度解析:XUnity.AutoTranslator的技术实现与工程实践 【免费下载链接】XUnity.AutoTranslator 项目地址: https://gitcode.com/gh_mirrors/xu/XUnity.AutoTranslator XUnity.AutoTranslator作为Unity游戏社区中最成熟的文本翻译解决方…

openEuler Raspberry Pi Kernel设备驱动开发指南:为树莓派硬件添加支持

openEuler Raspberry Pi Kernel设备驱动开发指南:为树莓派硬件添加支持

2026/7/17 17:34:09

openEuler Raspberry Pi Kernel设备驱动开发指南:为树莓派硬件添加支持 【免费下载链接】raspberrypi-kernel It provides openEuler kernel source for Raspberry Pi 项目地址: https://gitcode.com/openeuler/raspberrypi-kernel 前往项目官网免费下载&…

openEuler系统集成测试实战:基于smoke-test套件的环境验证技巧

openEuler系统集成测试实战:基于smoke-test套件的环境验证技巧

2026/7/16 14:18:17

openEuler系统集成测试实战:基于smoke-test套件的环境验证技巧 【免费下载链接】integration-test The repo contains test suits for system integration test 项目地址: https://gitcode.com/openeuler/integration-test 前往项目官网免费下载:…

从模糊意图到可执行指令:Claude PRD中Prompt Engineering与需求颗粒度的5级映射法则

从模糊意图到可执行指令:Claude PRD中Prompt Engineering与需求颗粒度的5级映射法则

2026/7/18 0:02:02

更多请点击: https://kaifayun.com 第一章:从模糊意图到可执行指令:Claude PRD中Prompt Engineering与需求颗粒度的5级映射法则 在Claude驱动的产品需求文档(PRD)生成实践中,原始业务意图往往以自然语言片…

Cursor配置生成失效?3大隐藏陷阱+4行修复代码,资深工程师连夜整理的紧急补救清单

Cursor配置生成失效?3大隐藏陷阱+4行修复代码,资深工程师连夜整理的紧急补救清单

2026/7/18 0:02:02

更多请点击: https://codechina.net 第一章:Cursor配置生成失效?3大隐藏陷阱4行修复代码,资深工程师连夜整理的紧急补救清单 Cursor 配置生成突然失效,是近期高频报障场景。表面看是 cursor.config.json 未更新或 LSP…

某智驾大牛创业

某智驾大牛创业

2026/7/18 0:02:02

作者:钟声编辑:Mark出品:红色星际头图:智能驾驶图片据悉,国内某头部智驾公司端到端模型技术大牛Z投身创业,并且已经拿到融资。Z不仅是该头部公司内部最年轻的对标阿里P10级别技术负责⼈,更是业内…