不理解@async的某些行为
我在理解 @async 注释的某些方面,以及线程和线程池作为一个整体的工作原理时遇到了一些困难。当我在 spring 配置文件中设置它时:
<task:executor id="WhifExecutor" pool-size="10"/>
<task:annotation-driven executor="WhifExecutor" />
这不是意味着只会启动 10 个线程吗?然而,当我运行一个具有 @async a 1000 次的函数时,它会在调用后立即继续执行其余代码(控制台中会显示一条简单的消息,以显示该函数被调用的次数)。然后过了一会儿,池化函数开始返回它们的值,但奇怪的是,仅从 1 个池和 10 个不同的线程返回它们的值。这是怎么回事?它如何调用所有这 1000 个函数却只使用 10 个线程?在启动线程之前,它是否可以将所有这些都放在某个堆栈上?我尝试阅读有关此问题的文档,但找不到有关此现象的任何信息。
另外,有没有办法让它等待线程开始运行,这样我就不会立即调用几千个函数?
I'm having some difficulty understanding a certain aspect of the @async annotation, and possibly the workings of threads and threadpooling as a whole. When I set this in my spring configuration file:
<task:executor id="WhifExecutor" pool-size="10"/>
<task:annotation-driven executor="WhifExecutor" />
wouldn't that mean only 10 threads will be started? Yet when I run a function that has @async a 1000 times it immediately continues with the rest of the code after the call (a simple message is shown in the console to show the number of times the function has been called). Then after a while the pooled functions start to return their values, but strangely enough only from 1 pool and 10 distinct threads. What is going on here? How can it call all those 1000 functions yet only use 10 threads? Does it maybe put all of them on some stack before starting the threads? I tried reading the documentation on this but I couldn't find anything about this phenomenon.
Also, is there a way to make it wait for threads to start running so that I don't immediately make a call to a couple thousand functions at once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不是堆栈,而是队列。
执行器将被分配10个线程。如果10个线程都忙,又有新的任务加入,就会被加入到队列中,依次执行。一次执行的任务不超过10个。
Not a stack, but a queue.
The executor will be allocated 10 threads. If all 10 threads are busy, and new tasks are added, they will be added to a queue, and executed in turn. No more than 10 tasks will be executed at one time.