java.util.concurrent.Executor 是如何工作的?
java.util.concurrent.Executor 如何创建“真正的”线程? 假设我正在实现 Executor 或使用任何执行器服务(如 ThreadPoolExecutor)。 JVM内部是如何工作的?
How does java.util.concurrent.Executor
create the "real" thread?
Suppose I am implementing Executor or using any executor service (like ThreadPoolExecutor). How does JVM internally work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它调用
ThreadFactory
。查看 Executors 类。请注意,它们都有一个重载参数,您可以在其中提供 ThreadFactory 实现。ThreadFactory
接口基本上是,如果没有提供,默认实现基本上只是
return new Thread(runnable);
为什么要覆盖它 - 它对于设置线程名称和守护进程状态等。
It calls
ThreadFactory
. Look at theExecutors
class. Note they all have an overloaded argument where you can supply aThreadFactory
implementation. TheThreadFactory
interface is basicallyand the default implementation if not supplied basically just is
return new Thread(runnable);
Why override this - well it's very useful for setting the Thread name and daemon status among other things.
Executor是现成的线程管理接口。
根据执行器的类型,它会创建一个或多个线程。线程完成后,其任务执行器将停止它们或保持运行。您还可以让执行程序运行计划任务(例如每分钟)。对于创建仅需要五秒的许多(通常是数千个线程)或不时使用的大量线程,这是一个很好的替代方案。
如果您指定要创建和提交的任务数量多于线程数量,则所有其他 Runnable 对象将排队等待轮到它们。这里没有 JVM 魔法,只有 Java 代码。
Executor is ready made thread management interface.
Depending on type of executor it creates one or more threads. After thread finishes its task executor stops them or leave running. You can also have executor that run scheduled tasks (for example every minute). This is good alternative for creating many (often thousand of threads) that are needed for just five seconds or plenty of threads that are used from time time.
If you specify number of threads to create and submit more tasks than thread quantity is -- all other Runnable objects will be queued until their turn will come. No JVM magic here just java code.