线程池-参数篇:3.ThreadFactory
2020-09-03 本文已影响0人
rock_fish
接口定义
public interface ThreadFactory {
/**
* Constructs a new {@code Thread}. Implementations may also initialize
* priority, name, daemon status, {@code ThreadGroup}, etc.
*
* @param r a runnable to be executed by new thread instance
* @return constructed thread, or {@code null} if the request to
* create a thread is rejected
*/
Thread newThread(Runnable r);
}
从注释中可知,通过ThreadFactory的newThread方法,可以对创建的线程做一些操控:
- 指定优先级
- 指定线程名称,方便监控
- 指定是否守护线程,守护线程不阻塞进程
- 指定线程组
默认的ThreadFactory
/**
* The default thread factory
*/
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
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;
}
}
默认线程池所创建的线程有一些特征:
- 名字有规律,形如 pool-N-thread-M (N:表示第几个线程池;M表示线程池内的第几个线程)
- 非守护线程,会阻塞进程退出,需要显式的关闭线程池
- 线程的优先级为:NORM_PRIORITY
自定义ThreadFactory
- 根据自己的需求,指定线程是否守护线程
- 定义识别度更高的线程名称
- 根据需要设置线程的优先级