执行器线程未终止
我正在使用 Executors.newFixedThreadPool(100) 方法。 单个命令执行大约需要 20 个线程。执行命令 5-6 次后,应用程序停止响应。 我的线程正在实现 Callable。
我怀疑该线程在完成后不会终止。 我还调用 shutdown() 来终止线程。
任何人都可以告诉我,当我使用 get() 方法检索线程的结果时,它是否被终止(意味着它从队列中删除)或者它仍然存在于队列中,池使用队列来存储线程。
I am using Executors.newFixedThreadPool(100) method.
Single command execution needs approx 20 threads. After executing the command 5-6 times, application stops responding.
My thread is implementing Callable.
I doubt, that thread doesn't terminate after completion.
I have also called shutdown() to terminate the thread.
Can anybody please tell, when I use get() method to retrieve the thread's result, does it gets terminated(means, its removed from the queue) or it is still there in the queue, which is used by pool to store the threads.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
线程不会终止。发生的情况是这样的:
,要么结果队列溢出,要么您的 Callable 不返回。
The threads don't terminate. What happens is this:
Callable
So either the result queue overflows or your
Callable
doesn't return.get()
是一个阻塞调用 - 这意味着调用线程将暂停,直到正在运行的线程完成其任务并且结果可用。执行器负责从队列中获取任务并进行清理,因此答案是“否” - 它不是“仍在队列中”
注意使用 100 个线程 - 这是一个高得离谱的数字。对于典型的机器,尝试使用 2 到 8 个线程(一切都取决于等待其他事情(例如 I/O)所花费的时间 - 您的任务受 CPU 限制越多,您应该使用的线程就越少。
get()
is a blocking call - that means the calling thread halts until the running thread has completed its task and the result is available.The Executor takes care of taking tasks from the queue and cleaning up, so the answer is "no" - it isn't "still on the queue"
Caution using 100 threads - that's a ridiculously high number. Try between 2 and 8 for a typical machine (all depends on how much time is spent waiting for other things eg I/O - the more CPU bound your tasks are, the less threads you should use.
即使在调用 get() 之后,线程仍会在队列中。事实上,API 确保即使一个线程死亡,它也会重新创建一个线程以保持“固定性”(固定池中的线程数)
请注意,如果池中的线程实际上正在执行某些任务(除了等待之外),调用 shutdown 不会终止线程。因此,例如,如果您的线程处于无限循环中做某事,那么调用 shutdown 是没有用的。
Even after calling get(), the thread would still be in the queue. Infact the API ensures that even if a thread dies, it recreates one to maintain "fixedness"(fixed no of threads in your pool)
Note that if the threads in your pool are actually doing some task(apart from waiting), calling shutdown will not terminate the thread. So, for e.g. if your threads are in a infinite loop doing something, then calling shutdown is useless.
调用 shutdown() 仅停止线程池接受新任务,并允许所有线程在所有任务执行完毕后完成。
你有多少个核心?如果您有 100 个繁忙的线程,并且假设有 4 个核心,则每个线程只会获得少量的 CPU 时间。
Calling shutdown() only stops the thread pool from accepting new tasks and allows all thread to finish once all tasks have been performed.
How many cores do you have? If you have 100 busy threads, and say 4 cores every thread is only going to get a small amount of CPU time.