不理解@async的某些行为

发布于 2024-10-02 07:29:46 字数 509 浏览 5 评论 0原文

我在理解 @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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

御弟哥哥 2024-10-09 07:29:46

在启动线程之前,它是否可能将所有这些都放在某个堆栈上?

不是堆栈,而是队列。

执行器将被分配10个线程。如果10个线程都忙,又有新的任务加入,就会被加入到队列中,依次执行。一次执行的任务不超过10个。

Does it maybe put all of them on some stack before starting the threads?

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文