How does java.util.concurrent.Executor work?

假如想象 提交于 2019-12-06 04:04:45

问题


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?


回答1:


It calls ThreadFactory. Look at the Executors class. Note they all have an overloaded argument where you can supply a ThreadFactory implementation. The ThreadFactory interface is basically

public Thread newThread(Runnable runnable);

and 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.




回答2:


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.



来源:https://stackoverflow.com/questions/5762991/how-does-java-util-concurrent-executor-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!