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