com.datastax.util.thread.DataExaThreadFactory Maven / Gradle / Ivy
package com.datastax.util.thread;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Hsuyung
* @date 2019/9/4.
*/
public class DataExaThreadFactory 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;
/**
* daemon为true,JVM不需要等待它退出,让JVM喜欢什么退出就退出吧,不用管它
*/
private final boolean daemon;
public DataExaThreadFactory() {
SecurityManager s = System.getSecurityManager();
//线程组
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
//名称前缀,这就是我们打印的线程池中线程名称前缀
//可以修改的,如果自定义线程工厂
namePrefix = "[DataExa] "+"pool-" +
poolNumber.getAndIncrement() +
"-thread-";
daemon = false;
}
public DataExaThreadFactory(String poolName) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "["+poolName+"] "+"pool-" +
poolNumber.getAndIncrement() +
"-thread-";
daemon = false;
}
public DataExaThreadFactory(String poolName, boolean isDaemon) {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "["+poolName+"] "+"pool-" +
poolNumber.getAndIncrement() +
"-thread-";
daemon = isDaemon;
}
@Override
public Thread newThread(Runnable runnable) {
Thread t = new Thread(group, runnable,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon()){
//非守护线程
t.setDaemon(daemon);
}
if (t.getPriority() != Thread.NORM_PRIORITY){
//常规优先级
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}