简体   繁体   中英

Differences between these 2 factory methods

I would like to know the difference between these 2 methods:

public static ExecutorService newFixedThreadPool(int nThreads)

and

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory tf)

Obviously one takes a specified ThreadFactory for threads creation. However I would like to know what kind of standard ThreadFactory the former use? Why is it convenient using the latter rather than the former or vice-versa? Thanks in advance.

DefaultThreadFactory ,

New threads are created using a ThreadFactory. If not otherwise specified, a Executors.defaultThreadFactory() is used, that creates threads to all be in the same java.lang.ThreadGroup and with the same NORM_PRIORITY priority and non-daemon status. By supplying a different ThreadFactory, you can alter the thread's name, thread group, priority, daemon status, etc. If a ThreadFactory fails to create a thread when asked by returning null from newThread, the executor will continue, but might not be able to execute any tasks. Threads should possess the "modifyThread" RuntimePermission. If worker threads or other threads using the pool do not possess this permission, service may be degraded: configuration changes may not take effect in a timely manner, and a shutdown pool may remain in a state in which termination is possible but not completed.

Reference -

But you can encapsulate the thread creation in your ThreadFactory , what actaully usage of Factory pattern .

For Example -

 class SimpleThreadFactory implements ThreadFactory {
   public Thread newThread(Runnable r) {
     // do something 
     return new Thread(r);
   }
 }

For reference please check - documentation and also find a good answer .

The first uses Executors.defaultThreadFactory to create threads with the first version. You would use the first version if you don't care how the threads are created, and the second if you need to impose some custom settings on the threads when they are created.

The first one uses the DefaultThreadFactory which is an inner class of Executors . When you define your own ThreadFactory you can influence the created Threads. You can choose their name, priority, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM