用ES6类实现支持并发控制的任务队列,核心是维护待执行任务队列和有限活跃槽位,通过Promise链与状态管理(maxConcurrency、running、queue)实现可控串行/并行调度。

在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
<p>用 ES6 类实现一个支持并发控制的任务队列,核心是维护一个待执行任务队列 + 有限数量的“活跃执行槽位”,通过 Promise 链和状态管理来串行/并行可控地运行异步任务。</p>
<H3>基础结构:任务存储与并发数控制</H3>
<p>类需保存:<strong>最大并发数(maxConcurrency)</strong>、<strong>当前运行中任务数(running)</strong>、<strong>等待队列(queue)</strong>。每次添加任务不立即执行,而是入队;有空闲槽位时才从队首取任务执行。</p>
<p>关键点:</p>
<ul>
<li>构造时指定 maxConcurrency,默认为 1(纯串行)</li>
<li>running 初始为 0,每开始一个任务加 1,结束减 1</li>
<li>每个任务包装成返回 Promise 的函数,便于统一 await 和错误处理</li>
</ul>
<H3>添加任务:入队 + 尝试启动</H3>
<p>提供 add() 方法接收一个异步函数(如 <font color="blue">() => fetch('/api')</font>),返回一个 Promise,让用户能 await 该任务结果。</p>
<p>实现逻辑:</p>
<ul>
<li>将任务和一个 resolve/reject 控制器一起推入 queue 数组</li>
<li>调用 tryRun():若 running < maxConcurrency,就取出队首任务执行,并增加 running</li>
<li>任务执行完毕(无论成功失败)必须调用 finish(),触发下一轮 tryRun()</li>
</ul>
<H3>执行调度:自动启停 + 错误透传</H3>
<p>任务执行后需确保:</p>
<ul>
<li>Promise 正常 resolve 或 reject,结果/错误原样暴露给调用 add() 的地方</li>
<li>执行完必须调用 finish(),减少 running 并检查 queue 是否还有待办任务</li>
<li>tryRun() 是递归驱动的核心:只要有空槽且有任务,就持续取、执行、减槽</li>
</ul>
<p>示例 finish() 内部会做:<font color="blue">running--; if (queue.length > 0) tryRun();</font></p>
<H3>完整可运行类代码</H3>
<p>以下是轻量、无依赖的实现:</p>
<pre><code class="js">class TaskQueue {
constructor(maxConcurrency = 1) {
this.maxConcurrency = Math.max(1, maxConcurrency);
this.running = 0;
this.queue = [];
}
add(taskFn) {
return new Promise((resolve, reject) => {
this.queue.push({ taskFn, resolve, reject });
this.tryRun();
});
}
tryRun() {
if (this.running >= this.maxConcurrency || this.queue.length === 0) return;
const { taskFn, resolve, reject } = this.queue.shift();
this.running++;
Promise.resolve()
.then(() => taskFn())
.then(result => {
resolve(result);
})
.catch(err => {
reject(err);
})
.finally(() => {
this.running--;
this.tryRun();
});
}
}</code></pre>
<p>使用示例:<br>
<font color="blue">const q = new TaskQueue(2);<br>
q.add(() => delay(1000).then(() => console.log('A')));<br>
q.add(() => delay(1000).then(() => console.log('B')));<br>
q.add(() => delay(1000).then(() => console.log('C'))); // A/B 并发,C 等待</font></p>

















