java - 这两种工厂方法之间的区别

标签 java threadpool factory

我想知道这两种方法之间的区别:

public static ExecutorService newFixedThreadPool(int nThreads)

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory tf)

显然,我们需要一个指定的 ThreadFactory 来创建线程。不过我想知道前者使用什么样的标准ThreadFactory? 为什么使用后者比前者更方便,反之亦然? 提前致谢。

最佳答案

默认线程工厂

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 -

但是你可以将线程创建封装在你的ThreadFactory中,这实际上是工厂模式的用法。

例如 -

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

如需引用,请查看 - documentation并且还找到了一个好的answer

关于java - 这两种工厂方法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17856983/

相关文章:

c# - 如何以线程安全的方式关闭表单(从后台线程使用)?

python - PyQt4中QWebView的多线程

java - 每个异步线程都运行一个无限循环

c++ - 无法推断返回类型的模板参数

Python:使用用户输入作为类名的类工厂

java - Spring:具有两个参数 setter 的配置 Bean

java - 从 Activity 向上导航到 fragment 打开相同的 fragment - Android 导航组件

python - 对象生成器模式

java - 二进制搜索树打印路径

java - 正则表达式从 00001 到 99999