对于Oracle来说,有一个open RFE。从Oracle员工的评论看来,他们似乎不了解这个问题,也无法解决问题。这是其中一种在JDK中很容易支持的事情(没有破坏向后兼容性),因此RFE被误解是一种遗憾。
正如你指出的那样,你需要实现你自己的ThreadFactory。如果您不想为此目的而使用Guava或Apache Commons,我在这里提供您可以使用的ThreadFactory
实现。它与您从JDK获得的内容完全相似,除了可以将线程名称前缀设置为“pool”之外的其他内容。
package org.demo.concurrency;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* ThreadFactory with the ability to set the thread name prefix.
* This class is exactly similar to
* {@link java.util.concurrent.Executors#defaultThreadFactory()}
* from JDK8, except for the thread naming feature.
*
* <p>
* The factory creates threads that have names on the form
* <i>prefix-N-thread-M</i>, where <i>prefix</i>
* is a string provided in the constructor, <i>N</i> is the sequence number of
* this factory, and <i>M</i> is the sequence number of the thread created
* by this factory.
*/
public class ThreadFactoryWithNamePrefix implements ThreadFactory {
// Note: The source code for this class was based entirely on
// Executors.DefaultThreadFactory class from the JDK8 source.
// The only change made is the ability to configure the thread
// name prefix.
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
/**
* Creates a new ThreadFactory where threads are created with a name prefix
* of <code>prefix</code>.
*
* @param prefix Thread name prefix. Never use a value of "pool" as in that
* case you might as well have used
* {@link java.util.concurrent.Executors#defaultThreadFactory()}.
*/
public ThreadFactoryWithNamePrefix(String prefix) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup()
: Thread.currentThread().getThreadGroup();
namePrefix = prefix + "-"
+ poolNumber.getAndIncrement()
+ "-thread-";
}
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
当你想使用它,你只需拿的事实,即所有Executors
方法允许你提供自己的ThreadFactory
。
这
Executors.newSingleThreadExecutor();
会给地方线程使用
Executors.newSingleThreadExecutor(new ThreadFactoryWithNamePrefix("primecalc");
你会得到其中的线程被命名为primecalc-N-thread-M
一个ExecutorService命名pool-N-thread-M
而是由ExecutorService的。瞧!
太棒了! – 2016-10-14 07:48:31