Java - Executors 有什么了不起的?
在没有 Java Executors 的生活中,必须为每个 Runnable 任务创建新线程。创建新线程需要线程开销(创建和拆卸),这会增加非执行程序程序的复杂性并浪费时间。
参考代码:
没有 Java Executor -
new Thread (aRunnableObject).start ();
使用 Java Executor -
Executor executor = some Executor factory method;
exector.execute (aRunnable);
底线是 Executors 抽象了如何管理线程的低级细节。
这是真的吗?
谢谢。
In a life without Java Executors, new threads would have to be created for each Runnable tasks. Making new threads requires thread overhead (creation and teardown) that adds complexity and wasted time to a non-Executor program.
Referring to code:
no Java Executor -
new Thread (aRunnableObject).start ();
with Java Executor -
Executor executor = some Executor factory method;
exector.execute (aRunnable);
Bottom line is that Executors abstract the low-level details of how to manage threads.
Is that true?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。
它们处理诸如创建线程对象、维护线程池、控制正在运行的线程数量以及优雅/不优雅关闭等问题。手工完成这些事情并不简单。
编辑
这样做可能会或可能不会影响性能...与完全适应应用程序的精确需求的自定义实现相比。但很可能是这样的:
此外,如果存在需要解决的问题,Executor 支持类允许您简单地调整各种参数(例如线程池大小)。我不知道使用 Executor 会如何显着影响垃圾收集开销,无论哪种方式。
作为一般规则,您应该专注于简单而稳健地编写应用程序(例如,使用高级并发支持类),并且仅在以下情况下担心性能:
Yes.
They deal with issues such as creating the thread objects, maintaining a pool of threads, controlling the number of threads are running, and graceful / less that graceful shutdown. Doing these things by hand is non-trivial.
EDIT
There may or may not be a performance hit in doing this ... compared with a custom implementation perfectly tuned to the precise needs of your application. But the chances are that:
Besides, the Executor support classes allow you to simply tune various parameters (e.g. thread pool sizes) if there is an issue that needs to be addressed. I don't see how garbage collection overheads would be significantly be impacted by using Executors, one way or the other.
As a general rule, you should focus on writing your applications simply and robustly (e.g. using the high level concurrency support classes), and only worry about performance if:
与普通线程相比,执行器有几个好处。
Couple of benefits of executors as against normal threads.