js按指定顺序执行任务队列

/**
 * @description: 实现功能:按指定顺序执行任务,如果该位置的任务没有进入队列,阻塞执行
 *                       只有等待该任务进入队列,继续开始执行该任务
 * @return {*}
 */

class TaskQueue {
  queue = [];
  running = false;
  nextIndex = 0;
  constructor() {
    this.queue = [];
    this.running = false;
    this.nextIndex = 0;
  }

  addTaskByIndex(index, task) {
    this.queue[index] = task;
    if (!this.running && this.nextIndex == index) {
      this.runByIndex();
    }
  }

  runByIndex() {
    // console.log('runByIndex', this.nextIndex, this.queue)
    const currentIndex = this.nextIndex;
    const task = this.queue[this.nextIndex];
    if (!task) return;
    this.running = true;
    task()
      .then(() => console.log(`任务${currentIndex}执行正常`))
      .catch(() => console.log(`任务${currentIndex}执行异常`))
      .finally(() => {
        this.running = false;
        this.nextIndex = currentIndex + 1;
        this.runByIndex();
      });
  }

  clear() {
    this.queue = [];
    this.nextIndex = 0;
    this.running = false;
  }
}

const taskQueue = new TaskQueue();

taskQueue.addTaskByIndex(0,
  () =>
    new Promise((resolve) =>
      setTimeout(() => {
        console.log(0);
        resolve();
      }, 100)
    )
);

taskQueue.addTaskByIndex(4,
  () =>
    new Promise((resolve) =>
      setTimeout(() => {
        console.log(4);
        resolve();
      }, 200)
    )
);

taskQueue.addTaskByIndex(2,
  () =>
    new Promise((resolve) =>
      setTimeout(() => {
        console.log(2);
        resolve();
      }, 300)
    )
);

taskQueue.addTaskByIndex(3,
  () =>
    new Promise((resolve) =>
      setTimeout(() => {
        console.log(3);
        resolve();
      }, 100)
    )
);

taskQueue.addTaskByIndex(1,
  () =>
    new Promise((resolve) =>
      setTimeout(() => {
        console.log(1);
        resolve();
      }, 100)
    )
);

// 按指定顺序任务0,1,2,3,4 输出0 1 2 3 4

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
任务队列结合线程池可以有效地利用多线程,提高程序的并发性和执行效率。一般来说,任务队列用于存储待执行任务,线程池则用于管理和调度线程的执行。下面是一个简单的示例代码: ```python import queue import threading # 定义任务队列 task_queue = queue.Queue() # 定义线程池 class ThreadPool: def __init__(self, num_threads): self.num_threads = num_threads self.threads = [] def start(self): for i in range(self.num_threads): t = threading.Thread(target=self.run) self.threads.append(t) t.start() def run(self): while True: task = task_queue.get() if task is None: break task() def join(self): for i in range(self.num_threads): task_queue.put(None) for t in self.threads: t.join() # 定义任务函数 def task_func(task_id): print(f'Task {task_id} executed') # 添加任务队列 for i in range(10): task_queue.put(lambda: task_func(i)) # 创建线程池并启动 thread_pool = ThreadPool(4) thread_pool.start() # 等待所有任务执行完成 thread_pool.join() ``` 在上述代码中,我们首先定义了一个任务队列 `task_queue`,然后定义了一个线程池 `ThreadPool`,包括 `start` 方法启动线程池,`run` 方法执行任务,以及 `join` 方法等待所有任务执行完成。接着,我们定义了一个任务函数 `task_func`,并将多个任务添加到队列中。最后,我们创建线程池并启动,等待所有任务执行完成。 在实际应用中,我们可以根据具体需求调整线程池的大小,以及任务队列的存储方式和任务执行逻辑,进一步优化程序的性能和可靠性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值