我想知道这两种方法之间的区别:
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.
但是你可以将线程创建封装在你的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/