<template>
<!-- -->
<div>
<el-button @click="buttonXc">点击开始渲染</el-button>
</div>
</template>
<script>
class ThreadPool { // 所有的工作线程
constructor(size) {
this.size = size; // size线程池的大小
this.tasks = []; // 待执行的任务队列
this.workers = []; // 空闲的工作线程队列
for (let i = 0; i < size; i++) {
const worker = new Worker();
this.workers.push(worker);
}
}
addTask(task) { // 添加任务
this.tasks.push(task);
this.dispatch();
}
dispatch() { // 分配任务给空闲的工作线程
while (this.tasks.length > 0 && this.workers.length > 0) { // 取出任务,并分配给空闲的工作线程
const task = this.tasks.shift();
const worker = this.workers.shift();
worker.run(task).then(() => {
this.workers.push(worker);
this.dispatch();
});
}
}
}
class Worker { // 工作线程
run(task) { // 执行任务, reject
return new Promise((resolve) => {
setTimeout(() => { // 执行的方法
console.log('渲染'+task);
resolve();
}, Math.random() * 1000);
});
}
}
export default {
data(){
return{
tasks:[]
}
},
created(){
},
methods:{
buttonXc(){
this.tasks = new ThreadPool(5);
this.xcList = 20
for(let i=0;i<this.xcList;i++){
this.tasks.addTask(i)
console.log(this.tasks.size); // 可以过去类的值
}
},
},
}
</script>
<style scoped>
</style>
在vue中使用线程池
最新推荐文章于 2024-05-05 21:50:34 发布