当前位置:首页 > 编程笔记 > 正文
已解决

并发任务队列(字节青训测试题)

来自网友在路上 163863提问 提问时间:2023-09-26 01:11:36阅读次数: 63

最佳答案 问答题库638位专家为你答疑解惑

需求描述

封装一个并发任务队列类,用于对一些异步任务按指定的并发数量进行并发执行。

/*** 延迟函数* @param {number} time - 延迟时间* @return {Promise} delayFn - 延迟函数(异步封装)*/
function timeout(time) {return new Promise((resolve) => {setTimeout(() => {resolve();}, time)});
}// 并发任务队列,接收一个最大并发数量
const concurrentTaskQueue = new ConcurrentTaskQueue(2);/*** 添加并发任务并按规则执行* @param {number} time - 延迟时间* @param {string} name - 任务名称*/
function addTask(time, name) {concurrentTaskQueue.add(() => timeout(time)).then(() => {console.log(`任务${name}完成`);})
}addTask(1000, 1);
addTask(1000, 2);
addTask(1000, 3);
addTask(1000, 4);
addTask(1000, 5);

实现

// 并发任务队列
class ConcurrentTaskQueue {constructor(concurrentCount) {this.concurrentCount = concurrentCount; // 并发数量this.tasks = []; // 任务队列this.runningCount = 0; // 正在执行的任务数量}// 添加任务add(task) {return new Promise((resolve) => {this.tasks.push({ task, resolve});this.handle(); // 添加完立即执行})}// 执行任务handle() {if (this.runningCount < this.concurrentCount && this.tasks.length > 0) {const { task, resolve} = this.tasks.shift(); // 取出任务this.runningCount++;task().then(resolve).finally(() => {this.runningCount--;this.handle(); // 执行完毕,并发数量有空余,再次调用})}}
}
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"并发任务队列(字节青训测试题)":http://eshow365.cn/6-13543-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!