mic*_*vka 0 javascript multithreading asynchronous node.js
我正在开发test nodejs app,我想创建100个"线程",每个线程使用setTimeOut在一些随机时间执行.
let count = 10;
let counter = 0;
for(let i = 0; i < count; i++) {
// call the rest of the code and have it execute after 3 seconds
setTimeout((async () => {
counter++;
console.log('executed thread',i, 'current counter is',counter);
if(counter === count){
console.log('all processed');
}
}), Math.random()*10);
console.log('executed setTimeOut number ',i);
}
console.log('main thread done, awaiting async');
Run Code Online (Sandbox Code Playgroud)
现在我不理解输出:
executed setTimeOut number 0
executed setTimeOut number 1
executed setTimeOut number 2
executed setTimeOut number 3
executed setTimeOut number 4
executed setTimeOut number 5
executed setTimeOut number 6
executed setTimeOut number 7
executed setTimeOut number 8
executed setTimeOut number 9
main thread done, awaiting async
executed thread 5 current counter is 1
executed thread 1 current counter is 2
executed thread 4 current counter is 3
executed thread 9 current counter is 4
executed thread 6 current counter is 5
executed thread 2 current counter is 6
executed thread 3 current counter is 7
executed thread 8 current counter is 8
executed thread 0 current counter is 9
executed thread 7 current counter is 10
all processed
Run Code Online (Sandbox Code Playgroud)
我期望executed thread X current counter is Y在executed setTimeOut number Z它之间混合,为什么它首先似乎将所有调用添加到setTimeOut并且只在执行它们之后?即使我将数量设定为1,000,000,这仍然会发生.这对我来说看起来不像预期的行为.
呼叫setTimeout同步发生.然后运行时有一堆排队的'任务',它可以在以后执行.当超时到期时,运行时可以自由选择这些任务并执行.因此,所有'执行的setTimeOut数'消息首先出现,然后是'执行的线程......'.
| 归档时间: |
|
| 查看次数: |
380 次 |
| 最近记录: |