序
出去面试遇到一个问题。
面试官:
有俩个队列,然后有若干任务。现在让第一个在队列1中执行,第二个在队列2中执行。
第三个在队列2中执行。第四个在队列。。。。。
当时就给我这青年老汉干蒙了。
因为天时地利人和都不占我。我脑子一抽抽,就往队列上猛地使劲。
后来面试完成后仔细一想。这™不就是js线程控制吗。
代码实现
class TaskQueue {
constructor(concurrentTasks) {
// 队列用于存储任务
this.queue = [];
// 当前运行的任务数量
this.runningNum = 0;
// 最大并发任务数量
this.maxConcurrentTasks = concurrentTasks || 2
}
addTask(task) {
// 每次执行都向队列中添加任务
this.queue.push(task);
// 添加完成后判断是否需要执行个任务
this.checkList()
}
checkList() {
const that = this
// 判断队列中是否还有任务,并且当前运行的任务数量小于最大并发数量,就执行任务
if (this.queue.length && this.runningNum < this.maxConcurrentTasks) {
this.runningNum += 1;
// 从队列中拿出第一个任务,并且执行
this.queue.shift()().then(() => {
that.runningNum -= 1;
// 执行完成后,继续判断队列中是否还有任务
// 应为用的是promise 异步,所以用 then 来触发后续逻辑。
// 没有用定时器来触发,因为定时器在执行中,如果没有达到触发条件,但是定时器还是会继续运行。浪费资源。
that.checkList()
});
}
}
}
测试
const taskQueue = new TaskQueue(2);
// 模拟执行,使用定时模拟异步任务
function executionTime(time, num) {
console.log('>>>开始执行任务;' + num);
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, time);
});
}
// 模拟任务
taskQueue.addTask(() => {
const time = 1000
return executionTime(time, 1).then(() => {
console.log(`<<<我是任务1,定时1秒`);
});
});
taskQueue.addTask(() => {
const time = 2000
return new Promise((resolve, reject) => {
executionTime(time, 2).then(() => {
console.log(`<<<我是任务2,定时2秒`);
resolve()
});
})
});
taskQueue.addTask(() => {
const time = 8000
return executionTime(time, 3).then(() => {
console.log(`<<<我是任务3,定时8秒`);
});
});
taskQueue.addTask(() => {
const time = 3000
return executionTime(time, 4).then(() => {
console.log(`<<<我是任务4,定时3秒`);
});
});
taskQueue.addTask(() => {
const time = 5000
return executionTime(time, 5).then(() => {
console.log(`<<<我是任务5,定时5秒`);
});
});
输出
Debugger listening on ws://127.0.0.1:3024/47e3e9e8-c015-4753-bd04-e70b00d3b9d0
For help, see: https://nodejs.org/en/docs/inspector
Debugger attached.
>>>开始执行任务;1
>>>开始执行任务;2
<<<我是任务1,定时1秒
>>>开始执行任务;3
<<<我是任务2,定时2秒
>>>开始执行任务;4
<<<我是任务4,定时3秒
>>>开始执行任务;5
<<<我是任务3,定时8秒
<<<我是任务5,定时5秒
Waiting for the debugger to disconnect...
PS D:\Code\exercise>
先执行了任务 1和 2。
因为 1 执行完成了,所以由 1 唤醒任务 3。
这时候 2 执行完成了,所以由 2 唤醒任务 4。
4 执行完成了,所以由 4 唤醒任务 5。
任务3执行完成, 队列中没有等待任务,结束。。
谢
本人在包头,希望可以找一份工作。。。
偏重前端
后端用 node